text stringlengths 198 433k | conversation_id int64 0 109k |
|---|---|
Provide tags and a correct Python 3 solution for this coding contest problem.
You are a lover of bacteria. You want to raise some bacteria in a box.
Initially, the box is empty. Each morning, you can put any number of bacteria into the box. And each night, every bacterium in the box will split into two bacteria. You hope to see exactly x bacteria in the box at some moment.
What is the minimum number of bacteria you need to put into the box across those days?
Input
The only line containing one integer x (1 β€ x β€ 109).
Output
The only line containing one integer: the answer.
Examples
Input
5
Output
2
Input
8
Output
1
Note
For the first sample, we can add one bacterium in the box in the first day morning and at the third morning there will be 4 bacteria in the box. Now we put one more resulting 5 in the box. We added 2 bacteria in the process so the answer is 2.
For the second sample, we can put one in the first morning and in the 4-th morning there will be 8 in the box. So the answer is 1.
Tags: bitmasks
Correct Solution:
```
x = int(input())
k = 0
while x > 0:
if x % 2 == 0:
x = x // 2
else:
k += 1
x -= 1
print(k)
```
| 84,600 |
Provide tags and a correct Python 3 solution for this coding contest problem.
You are a lover of bacteria. You want to raise some bacteria in a box.
Initially, the box is empty. Each morning, you can put any number of bacteria into the box. And each night, every bacterium in the box will split into two bacteria. You hope to see exactly x bacteria in the box at some moment.
What is the minimum number of bacteria you need to put into the box across those days?
Input
The only line containing one integer x (1 β€ x β€ 109).
Output
The only line containing one integer: the answer.
Examples
Input
5
Output
2
Input
8
Output
1
Note
For the first sample, we can add one bacterium in the box in the first day morning and at the third morning there will be 4 bacteria in the box. Now we put one more resulting 5 in the box. We added 2 bacteria in the process so the answer is 2.
For the second sample, we can put one in the first morning and in the 4-th morning there will be 8 in the box. So the answer is 1.
Tags: bitmasks
Correct Solution:
```
def binary(n):
while n > 0:
yield n % 2
n //= 2
def main():
n = int(input())
print(sum(binary(n)))
if __name__ == '__main__':
main()
```
| 84,601 |
Provide tags and a correct Python 3 solution for this coding contest problem.
You are a lover of bacteria. You want to raise some bacteria in a box.
Initially, the box is empty. Each morning, you can put any number of bacteria into the box. And each night, every bacterium in the box will split into two bacteria. You hope to see exactly x bacteria in the box at some moment.
What is the minimum number of bacteria you need to put into the box across those days?
Input
The only line containing one integer x (1 β€ x β€ 109).
Output
The only line containing one integer: the answer.
Examples
Input
5
Output
2
Input
8
Output
1
Note
For the first sample, we can add one bacterium in the box in the first day morning and at the third morning there will be 4 bacteria in the box. Now we put one more resulting 5 in the box. We added 2 bacteria in the process so the answer is 2.
For the second sample, we can put one in the first morning and in the 4-th morning there will be 8 in the box. So the answer is 1.
Tags: bitmasks
Correct Solution:
```
n=int(input())
c=0
while n>1:
if n%2==1:
c=c+1
n=n//2
print(c+1)
```
| 84,602 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
You are a lover of bacteria. You want to raise some bacteria in a box.
Initially, the box is empty. Each morning, you can put any number of bacteria into the box. And each night, every bacterium in the box will split into two bacteria. You hope to see exactly x bacteria in the box at some moment.
What is the minimum number of bacteria you need to put into the box across those days?
Input
The only line containing one integer x (1 β€ x β€ 109).
Output
The only line containing one integer: the answer.
Examples
Input
5
Output
2
Input
8
Output
1
Note
For the first sample, we can add one bacterium in the box in the first day morning and at the third morning there will be 4 bacteria in the box. Now we put one more resulting 5 in the box. We added 2 bacteria in the process so the answer is 2.
For the second sample, we can put one in the first morning and in the 4-th morning there will be 8 in the box. So the answer is 1.
Submitted Solution:
```
n = int(input())
s = 0
while n > 0:
if n % 2 == 1:
n -= 1
s += 1
else:
n //= 2
print(s)
```
Yes
| 84,603 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
You are a lover of bacteria. You want to raise some bacteria in a box.
Initially, the box is empty. Each morning, you can put any number of bacteria into the box. And each night, every bacterium in the box will split into two bacteria. You hope to see exactly x bacteria in the box at some moment.
What is the minimum number of bacteria you need to put into the box across those days?
Input
The only line containing one integer x (1 β€ x β€ 109).
Output
The only line containing one integer: the answer.
Examples
Input
5
Output
2
Input
8
Output
1
Note
For the first sample, we can add one bacterium in the box in the first day morning and at the third morning there will be 4 bacteria in the box. Now we put one more resulting 5 in the box. We added 2 bacteria in the process so the answer is 2.
For the second sample, we can put one in the first morning and in the 4-th morning there will be 8 in the box. So the answer is 1.
Submitted Solution:
```
n=int(input())
b=bin(n)
l=list(b)
print(l.count('1'))
```
Yes
| 84,604 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
You are a lover of bacteria. You want to raise some bacteria in a box.
Initially, the box is empty. Each morning, you can put any number of bacteria into the box. And each night, every bacterium in the box will split into two bacteria. You hope to see exactly x bacteria in the box at some moment.
What is the minimum number of bacteria you need to put into the box across those days?
Input
The only line containing one integer x (1 β€ x β€ 109).
Output
The only line containing one integer: the answer.
Examples
Input
5
Output
2
Input
8
Output
1
Note
For the first sample, we can add one bacterium in the box in the first day morning and at the third morning there will be 4 bacteria in the box. Now we put one more resulting 5 in the box. We added 2 bacteria in the process so the answer is 2.
For the second sample, we can put one in the first morning and in the 4-th morning there will be 8 in the box. So the answer is 1.
Submitted Solution:
```
N = bin(int(input()))
cnt = 0
for i in range(2, len(N)):
if N[i] == '1':
cnt += 1
print(cnt)
```
Yes
| 84,605 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
You are a lover of bacteria. You want to raise some bacteria in a box.
Initially, the box is empty. Each morning, you can put any number of bacteria into the box. And each night, every bacterium in the box will split into two bacteria. You hope to see exactly x bacteria in the box at some moment.
What is the minimum number of bacteria you need to put into the box across those days?
Input
The only line containing one integer x (1 β€ x β€ 109).
Output
The only line containing one integer: the answer.
Examples
Input
5
Output
2
Input
8
Output
1
Note
For the first sample, we can add one bacterium in the box in the first day morning and at the third morning there will be 4 bacteria in the box. Now we put one more resulting 5 in the box. We added 2 bacteria in the process so the answer is 2.
For the second sample, we can put one in the first morning and in the 4-th morning there will be 8 in the box. So the answer is 1.
Submitted Solution:
```
n = int(input())
x=0
while n>=1:
if n%2==1:
x+=1
n-=1
else:
n//=2;
print(x)
```
Yes
| 84,606 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
You are a lover of bacteria. You want to raise some bacteria in a box.
Initially, the box is empty. Each morning, you can put any number of bacteria into the box. And each night, every bacterium in the box will split into two bacteria. You hope to see exactly x bacteria in the box at some moment.
What is the minimum number of bacteria you need to put into the box across those days?
Input
The only line containing one integer x (1 β€ x β€ 109).
Output
The only line containing one integer: the answer.
Examples
Input
5
Output
2
Input
8
Output
1
Note
For the first sample, we can add one bacterium in the box in the first day morning and at the third morning there will be 4 bacteria in the box. Now we put one more resulting 5 in the box. We added 2 bacteria in the process so the answer is 2.
For the second sample, we can put one in the first morning and in the 4-th morning there will be 8 in the box. So the answer is 1.
Submitted Solution:
```
n = int(input())
number = ''
while n > 0:
x = str(n % 2)
number = x + number
n = n // 2
```
No
| 84,607 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
You are a lover of bacteria. You want to raise some bacteria in a box.
Initially, the box is empty. Each morning, you can put any number of bacteria into the box. And each night, every bacterium in the box will split into two bacteria. You hope to see exactly x bacteria in the box at some moment.
What is the minimum number of bacteria you need to put into the box across those days?
Input
The only line containing one integer x (1 β€ x β€ 109).
Output
The only line containing one integer: the answer.
Examples
Input
5
Output
2
Input
8
Output
1
Note
For the first sample, we can add one bacterium in the box in the first day morning and at the third morning there will be 4 bacteria in the box. Now we put one more resulting 5 in the box. We added 2 bacteria in the process so the answer is 2.
For the second sample, we can put one in the first morning and in the 4-th morning there will be 8 in the box. So the answer is 1.
Submitted Solution:
```
n = int(input())
i = 2
while i * 2 <= n:
i *= 2
print(n - i + 1)
```
No
| 84,608 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
You are a lover of bacteria. You want to raise some bacteria in a box.
Initially, the box is empty. Each morning, you can put any number of bacteria into the box. And each night, every bacterium in the box will split into two bacteria. You hope to see exactly x bacteria in the box at some moment.
What is the minimum number of bacteria you need to put into the box across those days?
Input
The only line containing one integer x (1 β€ x β€ 109).
Output
The only line containing one integer: the answer.
Examples
Input
5
Output
2
Input
8
Output
1
Note
For the first sample, we can add one bacterium in the box in the first day morning and at the third morning there will be 4 bacteria in the box. Now we put one more resulting 5 in the box. We added 2 bacteria in the process so the answer is 2.
For the second sample, we can put one in the first morning and in the 4-th morning there will be 8 in the box. So the answer is 1.
Submitted Solution:
```
n=int(input())
if n%2==0 and n>0:
print(1)
elif n==0:
print(0)
else:
b=1+(int(n/2)-1)*2
print(n-b)
##hi
```
No
| 84,609 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
You are a lover of bacteria. You want to raise some bacteria in a box.
Initially, the box is empty. Each morning, you can put any number of bacteria into the box. And each night, every bacterium in the box will split into two bacteria. You hope to see exactly x bacteria in the box at some moment.
What is the minimum number of bacteria you need to put into the box across those days?
Input
The only line containing one integer x (1 β€ x β€ 109).
Output
The only line containing one integer: the answer.
Examples
Input
5
Output
2
Input
8
Output
1
Note
For the first sample, we can add one bacterium in the box in the first day morning and at the third morning there will be 4 bacteria in the box. Now we put one more resulting 5 in the box. We added 2 bacteria in the process so the answer is 2.
For the second sample, we can put one in the first morning and in the 4-th morning there will be 8 in the box. So the answer is 1.
Submitted Solution:
```
n = int(input())
print(1+((n & (n-1) != 0) or n == 0))
```
No
| 84,610 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Everyone knows that long ago on the territory of present-day Berland there lived Bindian tribes. Their capital was surrounded by n hills, forming a circle. On each hill there was a watchman, who watched the neighbourhood day and night.
In case of any danger the watchman could make a fire on the hill. One watchman could see the signal of another watchman, if on the circle arc connecting the two hills there was no hill higher than any of the two. As for any two hills there are two different circle arcs connecting them, the signal was seen if the above mentioned condition was satisfied on at least one of the arcs. For example, for any two neighbouring watchmen it is true that the signal of one will be seen by the other.
An important characteristics of this watch system was the amount of pairs of watchmen able to see each other's signals. You are to find this amount by the given heights of the hills.
Input
The first line of the input data contains an integer number n (3 β€ n β€ 106), n β the amount of hills around the capital. The second line contains n numbers β heights of the hills in clockwise order. All height numbers are integer and lie between 1 and 109.
Output
Print the required amount of pairs.
Examples
Input
5
1 2 4 5 3
Output
7
Tags: data structures
Correct Solution:
```
n = int(input())
a = list(map(int, input().split()))
top = max(a)
stack = [[10 ** 9 + 1, 1]]
ans = 0
for i in range(n):
while a[i] > stack[-1][0]:
stack.pop()
if a[i] < stack[-1][0]:
stack.append([a[i], 1])
else:
stack[-1][1] += 1
for i in range(n):
cnt = 0
while a[i] > stack[-1][0]:
cnt += stack[-1][1]
stack.pop()
if a[i] < stack[-1][0]:
cnt += 1
stack.append([a[i], 1])
else:
if a[i] < top:
cnt += stack[-1][1]
if stack[-2][1] != 0:
cnt += 1
stack[-1][1] += 1
ans += cnt
topcnt = a.count(top)
ans += topcnt * (topcnt - 1) // 2
if topcnt == 1:
second = max(a, key=lambda x: (x != top) * x)
seccnt = a.count(second)
ans -= seccnt
print(ans)
```
| 84,611 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Everyone knows that long ago on the territory of present-day Berland there lived Bindian tribes. Their capital was surrounded by n hills, forming a circle. On each hill there was a watchman, who watched the neighbourhood day and night.
In case of any danger the watchman could make a fire on the hill. One watchman could see the signal of another watchman, if on the circle arc connecting the two hills there was no hill higher than any of the two. As for any two hills there are two different circle arcs connecting them, the signal was seen if the above mentioned condition was satisfied on at least one of the arcs. For example, for any two neighbouring watchmen it is true that the signal of one will be seen by the other.
An important characteristics of this watch system was the amount of pairs of watchmen able to see each other's signals. You are to find this amount by the given heights of the hills.
Input
The first line of the input data contains an integer number n (3 β€ n β€ 106), n β the amount of hills around the capital. The second line contains n numbers β heights of the hills in clockwise order. All height numbers are integer and lie between 1 and 109.
Output
Print the required amount of pairs.
Examples
Input
5
1 2 4 5 3
Output
7
Tags: data structures
Correct Solution:
```
n = int(input())
a = list(map(int, input().split()))
max_idx = a.index(max(a))
b = a[max_idx:]
b.extend(a[:max_idx])
b.append(a[max_idx])
left = [0] * (n + 1)
right = [n] * (n + 1)
cnt = [0] * (n + 1)
for i in range(1, n):
idx = i - 1
while b[idx] <= b[i] and idx > 0:
idx = left[idx]
left[i] = idx
for i in range(n - 1, 0, -1):
idx = i + 1
while b[idx] <= b[i] and idx < n:
if b[idx] == b[i] and idx < n:
cnt[i] = cnt[idx] + 1
idx = right[idx]
right[i] = idx
res = 0
for i in range(1, n):
if left[i] == 0 and right[i] == n:
res += 1
else:
res += 2
res += cnt[i]
print(res)
```
| 84,612 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Everyone knows that long ago on the territory of present-day Berland there lived Bindian tribes. Their capital was surrounded by n hills, forming a circle. On each hill there was a watchman, who watched the neighbourhood day and night.
In case of any danger the watchman could make a fire on the hill. One watchman could see the signal of another watchman, if on the circle arc connecting the two hills there was no hill higher than any of the two. As for any two hills there are two different circle arcs connecting them, the signal was seen if the above mentioned condition was satisfied on at least one of the arcs. For example, for any two neighbouring watchmen it is true that the signal of one will be seen by the other.
An important characteristics of this watch system was the amount of pairs of watchmen able to see each other's signals. You are to find this amount by the given heights of the hills.
Input
The first line of the input data contains an integer number n (3 β€ n β€ 106), n β the amount of hills around the capital. The second line contains n numbers β heights of the hills in clockwise order. All height numbers are integer and lie between 1 and 109.
Output
Print the required amount of pairs.
Examples
Input
5
1 2 4 5 3
Output
7
Tags: data structures
Correct Solution:
```
n = int(input())
arr = list(map(int, input().split()))
max_idx = 0
for i in range(1, n):
if arr[i] >= arr[max_idx]:
max_idx = i
arr2 = arr[max_idx:]
arr2.extend(arr[0:max_idx])
dp_left = [-1 for i in range(0, n)]
for i in range(1, n):
prev = i - 1
while prev >= 0 and arr2[prev] <= arr2[i]:
prev = dp_left[prev]
dp_left[i] = prev
dp_right = [0 for i in range(0, n)]
dp_right[0] = -1
for i in range(n - 1, 0, -1):
prev = i + 1
if prev == n:
prev = 0
while prev >= 0 and arr2[prev] <= arr2[i]:
prev = dp_right[prev]
dp_right[i] = prev
dp_same = [0 for i in range(0, n)]
for i in range(0, n):
prev = i - 1
while prev >= 0 and arr2[prev] < arr2[i]:
prev = dp_left[prev]
if prev >= 0 and arr2[prev] == arr2[i]:
dp_same[i] = dp_same[prev] + 1
res = 0
for i in range(0, n):
if dp_left[i] == dp_right[i] and dp_left[i] >= 0:
res += 1
else:
if dp_left[i] >= 0:
res += 1
if dp_right[i] >= 0:
res += 1
res += dp_same[i]
print(res)
```
| 84,613 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Everyone knows that long ago on the territory of present-day Berland there lived Bindian tribes. Their capital was surrounded by n hills, forming a circle. On each hill there was a watchman, who watched the neighbourhood day and night.
In case of any danger the watchman could make a fire on the hill. One watchman could see the signal of another watchman, if on the circle arc connecting the two hills there was no hill higher than any of the two. As for any two hills there are two different circle arcs connecting them, the signal was seen if the above mentioned condition was satisfied on at least one of the arcs. For example, for any two neighbouring watchmen it is true that the signal of one will be seen by the other.
An important characteristics of this watch system was the amount of pairs of watchmen able to see each other's signals. You are to find this amount by the given heights of the hills.
Input
The first line of the input data contains an integer number n (3 β€ n β€ 106), n β the amount of hills around the capital. The second line contains n numbers β heights of the hills in clockwise order. All height numbers are integer and lie between 1 and 109.
Output
Print the required amount of pairs.
Examples
Input
5
1 2 4 5 3
Output
7
Tags: data structures
Correct Solution:
```
#!/usr/bin/env python
def main():
n = int(input())
hill = tuple(map(int, input().split()))
pairs = 0
highest, at = max((h, k) for k, h in enumerate(hill))
last = highest
count = 0
previous = list()
push = previous.append
pop = previous.pop
for at in range(at - 1, at - n, -1):
current = hill[at]
while current > last:
pairs += count
last, count = pop()
if current == last:
count += 1
pairs += count
else:
pairs += 1
push((last, count))
last = current
count = 1
push((last, count))
end = len(previous)
pairs += sum(previous[k][1]
for k in range((1 if previous[0][1] else 2), end))
print(pairs)
if __name__ == '__main__':
main()
```
| 84,614 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Everyone knows that long ago on the territory of present-day Berland there lived Bindian tribes. Their capital was surrounded by n hills, forming a circle. On each hill there was a watchman, who watched the neighbourhood day and night.
In case of any danger the watchman could make a fire on the hill. One watchman could see the signal of another watchman, if on the circle arc connecting the two hills there was no hill higher than any of the two. As for any two hills there are two different circle arcs connecting them, the signal was seen if the above mentioned condition was satisfied on at least one of the arcs. For example, for any two neighbouring watchmen it is true that the signal of one will be seen by the other.
An important characteristics of this watch system was the amount of pairs of watchmen able to see each other's signals. You are to find this amount by the given heights of the hills.
Input
The first line of the input data contains an integer number n (3 β€ n β€ 106), n β the amount of hills around the capital. The second line contains n numbers β heights of the hills in clockwise order. All height numbers are integer and lie between 1 and 109.
Output
Print the required amount of pairs.
Examples
Input
5
1 2 4 5 3
Output
7
Tags: data structures
Correct Solution:
```
n = int(input())
a = tuple(map(int, input().split()))
b = 0
c, at = max((h, k) for k, h in enumerate(a))
last = c
count = 0
d = list()
e = d.append
f = d.pop
for at in range(at - 1, at - n, -1):
current = a[at]
while current > last:
b += count
last, count = f()
if current == last:
count += 1
b += count
else:
b += 1
e((last, count))
last = current
count = 1
e((last, count))
end = len(d)
b += sum(d[k][1] for k in range((1 if d[0][1] else 2), end))
print(b)
```
| 84,615 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Everyone knows that long ago on the territory of present-day Berland there lived Bindian tribes. Their capital was surrounded by n hills, forming a circle. On each hill there was a watchman, who watched the neighbourhood day and night.
In case of any danger the watchman could make a fire on the hill. One watchman could see the signal of another watchman, if on the circle arc connecting the two hills there was no hill higher than any of the two. As for any two hills there are two different circle arcs connecting them, the signal was seen if the above mentioned condition was satisfied on at least one of the arcs. For example, for any two neighbouring watchmen it is true that the signal of one will be seen by the other.
An important characteristics of this watch system was the amount of pairs of watchmen able to see each other's signals. You are to find this amount by the given heights of the hills.
Input
The first line of the input data contains an integer number n (3 β€ n β€ 106), n β the amount of hills around the capital. The second line contains n numbers β heights of the hills in clockwise order. All height numbers are integer and lie between 1 and 109.
Output
Print the required amount of pairs.
Examples
Input
5
1 2 4 5 3
Output
7
Tags: data structures
Correct Solution:
```
n = int(input())
hill = tuple(map(int, input().split()))
pairs = 0
highest, at = max((h, k) for k, h in enumerate(hill))
last = highest
count = 0
p = list()
push = p.append
pop = p.pop
for at in range(at - 1, at - n, -1):
current = hill[at]
while current > last:
pairs += count
last, count = pop()
if current == last:
count += 1
pairs += count
else:
pairs += 1
push((last, count))
last = current
count = 1
push((last, count))
end = len(p)
pairs += sum(p[k][1]
for k in range((1 if p[0][1] else 2), end))
print(pairs)
```
| 84,616 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Everyone knows that long ago on the territory of present-day Berland there lived Bindian tribes. Their capital was surrounded by n hills, forming a circle. On each hill there was a watchman, who watched the neighbourhood day and night.
In case of any danger the watchman could make a fire on the hill. One watchman could see the signal of another watchman, if on the circle arc connecting the two hills there was no hill higher than any of the two. As for any two hills there are two different circle arcs connecting them, the signal was seen if the above mentioned condition was satisfied on at least one of the arcs. For example, for any two neighbouring watchmen it is true that the signal of one will be seen by the other.
An important characteristics of this watch system was the amount of pairs of watchmen able to see each other's signals. You are to find this amount by the given heights of the hills.
Input
The first line of the input data contains an integer number n (3 β€ n β€ 106), n β the amount of hills around the capital. The second line contains n numbers β heights of the hills in clockwise order. All height numbers are integer and lie between 1 and 109.
Output
Print the required amount of pairs.
Examples
Input
5
1 2 4 5 3
Output
7
Tags: data structures
Correct Solution:
```
n = int(input())
arr = list(map(int, input().split()))
max_idx = 0
for i in range(1, n):
if arr[i] >= arr[max_idx]:
max_idx = i
arr2 = arr[max_idx:]
arr2.extend(arr[0:max_idx])
# print(arr2)
# for i in range(max_idx, n):
# arr2.append(arr[i])
# for i in range(0, max_idx):
# arr2.append(arr[i])
dp_left = [-1 for i in range(0, n)]
for i in range(1, n):
prev = i - 1
while prev >= 0 and arr2[prev] <= arr2[i]:
prev = dp_left[prev]
dp_left[i] = prev
dp_right = [0 for i in range(0, n)]
dp_right[0] = -1
# dp_right[n - 1] = 0
for i in range(n - 1, 0, -1):
prev = i + 1
if prev == n:
prev = 0
while prev >= 0 and arr2[prev] <= arr2[i]:
prev = dp_right[prev]
dp_right[i] = prev
dp_same = [0 for i in range(0, n)]
for i in range(0, n):
prev = i - 1
while prev >= 0 and arr2[prev] < arr2[i]:
prev = dp_left[prev]
if prev >= 0 and arr2[prev] == arr2[i]:
dp_same[i] = dp_same[prev] + 1
# print(arr2)
# print(dp_left)
# print(dp_right)
# print(dp_same)
res = 0
for i in range(0, n):
if dp_left[i] == dp_right[i] and dp_left[i] >= 0:
res += 1
else:
if dp_left[i] >= 0:
res += 1
if dp_right[i] >= 0:
res += 1
res += dp_same[i]
print(res)
```
| 84,617 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Everyone knows that long ago on the territory of present-day Berland there lived Bindian tribes. Their capital was surrounded by n hills, forming a circle. On each hill there was a watchman, who watched the neighbourhood day and night.
In case of any danger the watchman could make a fire on the hill. One watchman could see the signal of another watchman, if on the circle arc connecting the two hills there was no hill higher than any of the two. As for any two hills there are two different circle arcs connecting them, the signal was seen if the above mentioned condition was satisfied on at least one of the arcs. For example, for any two neighbouring watchmen it is true that the signal of one will be seen by the other.
An important characteristics of this watch system was the amount of pairs of watchmen able to see each other's signals. You are to find this amount by the given heights of the hills.
Input
The first line of the input data contains an integer number n (3 β€ n β€ 106), n β the amount of hills around the capital. The second line contains n numbers β heights of the hills in clockwise order. All height numbers are integer and lie between 1 and 109.
Output
Print the required amount of pairs.
Examples
Input
5
1 2 4 5 3
Output
7
Tags: data structures
Correct Solution:
```
n = int(input())
a = list(map(int, input().split()))
top = max(a)
stack = [[10 ** 9 + 1, 0, -1]]
ans = 0
for i in range(n):
while a[i] > stack[-1][0]:
stack.pop()
if a[i] < stack[-1][0]:
stack.append([a[i], 1, i, i])
else:
stack[-1][1] += 1
stack[-1][3] = i
for i in range(n):
#print(stack)
cnt = 0
while a[i] > stack[-1][0]:
cnt += stack[-1][1]
#if (i - stack[-1][2]) % n == n - 1:
# cnt -= 1
stack.pop()
if a[i] < stack[-1][0]:
#if (i - stack[-1][3]) % n != n - 1:
cnt += 1
stack.append([a[i], 1, i, i])
else:
if a[i] < top:
cnt += stack[-1][1]
if stack[-2][1] != 0:# and (i - stack[-2][3]) % n != n - 1:
cnt += 1
stack[-1][1] += 1
stack[-1][3] = i
ans += cnt
#print(a[i], cnt)
topcnt = a.count(top)
ans += topcnt * (topcnt - 1) // 2
if topcnt == 1:
second = max(a, key=lambda x: (x != top) * x)
seccnt = a.count(second)
ans -= seccnt
print(ans)
```
| 84,618 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Everyone knows that long ago on the territory of present-day Berland there lived Bindian tribes. Their capital was surrounded by n hills, forming a circle. On each hill there was a watchman, who watched the neighbourhood day and night.
In case of any danger the watchman could make a fire on the hill. One watchman could see the signal of another watchman, if on the circle arc connecting the two hills there was no hill higher than any of the two. As for any two hills there are two different circle arcs connecting them, the signal was seen if the above mentioned condition was satisfied on at least one of the arcs. For example, for any two neighbouring watchmen it is true that the signal of one will be seen by the other.
An important characteristics of this watch system was the amount of pairs of watchmen able to see each other's signals. You are to find this amount by the given heights of the hills.
Input
The first line of the input data contains an integer number n (3 β€ n β€ 106), n β the amount of hills around the capital. The second line contains n numbers β heights of the hills in clockwise order. All height numbers are integer and lie between 1 and 109.
Output
Print the required amount of pairs.
Examples
Input
5
1 2 4 5 3
Output
7
Submitted Solution:
```
n = int(input())
hs = list(map(int, input().split()))
maxi = hs.index(max(hs))
# linearise
hs = hs[maxi:] + hs[:maxi]
hs.append(hs[0])
rs = [n]*(n+1)
ls = [0]*(n+1)
ss = [0]*(n+1)
for i in range(n-1, -1, -1):
rs[i] = i+1
while rs[i] < n and hs[i] > hs[rs[i]]:
rs[i] = rs[rs[i]]
if rs[i] < n and hs[i] == hs[rs[i]]:
ss[i] = ss[rs[i]] + 1
rs[i] = rs[rs[i]]
ans = ss[0]
for i in range(1, n+1):
ls[i] = i-1
while ls[i] > 0 and hs[i] >= hs[ls[i]]:
ls[i] = ls[ls[i]]
if hs[i] < hs[ls[i]]:
#print(i, ls[i])
ans += 1
if hs[i] < hs[rs[i]] and (ls[i] != 0 or rs[i] != n):
#print(i, rs[i])
ans += 1
ans += ss[i]
#print(ls)
#print(rs)
#print(ss)
print(ans)
```
Yes
| 84,619 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Everyone knows that long ago on the territory of present-day Berland there lived Bindian tribes. Their capital was surrounded by n hills, forming a circle. On each hill there was a watchman, who watched the neighbourhood day and night.
In case of any danger the watchman could make a fire on the hill. One watchman could see the signal of another watchman, if on the circle arc connecting the two hills there was no hill higher than any of the two. As for any two hills there are two different circle arcs connecting them, the signal was seen if the above mentioned condition was satisfied on at least one of the arcs. For example, for any two neighbouring watchmen it is true that the signal of one will be seen by the other.
An important characteristics of this watch system was the amount of pairs of watchmen able to see each other's signals. You are to find this amount by the given heights of the hills.
Input
The first line of the input data contains an integer number n (3 β€ n β€ 106), n β the amount of hills around the capital. The second line contains n numbers β heights of the hills in clockwise order. All height numbers are integer and lie between 1 and 109.
Output
Print the required amount of pairs.
Examples
Input
5
1 2 4 5 3
Output
7
Submitted Solution:
```
"""
Codeforces
5E - Bindian Signalizing
http://codeforces.com/contest/5/problem/E
HΓ©ctor GonzΓ‘lez Belver
../07/2018
"""
import sys
import itertools
def rotation(iterable, n, start):
for i in range(n):
yield iterable[(i+start)%n]
def main():
n = int(sys.stdin.readline().strip())
hills = list(map(int,sys.stdin.readline().strip().split()))
max_height, pos_max_height = max((h, i) for i, h in enumerate(hills))
reference_height = max_height
reference_cost = 0
pairs = 0
reference_hills = []
for current_height in itertools.islice(rotation(hills, n, pos_max_height+1), n-1):
while current_height > reference_height:
pairs += reference_cost
reference_height, reference_cost = reference_hills.pop()
if current_height == reference_height:
reference_cost += 1
pairs += reference_cost
else:
pairs += 1
reference_hills.append((reference_height, reference_cost))
reference_height = current_height
reference_cost = 1
reference_hills.append((reference_height, reference_cost))
start = 1 if reference_hills[0][1] else 2
pairs += sum(reference_hills[i][1] for i in range(start, len(reference_hills)))
sys.stdout.write(str(pairs) + '\n')
if __name__ == '__main__':
main()
```
Yes
| 84,620 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Everyone knows that long ago on the territory of present-day Berland there lived Bindian tribes. Their capital was surrounded by n hills, forming a circle. On each hill there was a watchman, who watched the neighbourhood day and night.
In case of any danger the watchman could make a fire on the hill. One watchman could see the signal of another watchman, if on the circle arc connecting the two hills there was no hill higher than any of the two. As for any two hills there are two different circle arcs connecting them, the signal was seen if the above mentioned condition was satisfied on at least one of the arcs. For example, for any two neighbouring watchmen it is true that the signal of one will be seen by the other.
An important characteristics of this watch system was the amount of pairs of watchmen able to see each other's signals. You are to find this amount by the given heights of the hills.
Input
The first line of the input data contains an integer number n (3 β€ n β€ 106), n β the amount of hills around the capital. The second line contains n numbers β heights of the hills in clockwise order. All height numbers are integer and lie between 1 and 109.
Output
Print the required amount of pairs.
Examples
Input
5
1 2 4 5 3
Output
7
Submitted Solution:
```
n = int(input())
hills = list(map(int, input().strip().split()))
max_height, pos_max_height = max((h, i) for i, h in enumerate(hills))
rotation_hill=(hills[pos_max_height:]+hills[:pos_max_height])[1:]
reference_height = max_height
reference_cost = 0
pairs = 0
reference_hills = []
for current_height in rotation_hill:
while current_height > reference_height:
pairs += reference_cost
reference_height, reference_cost = reference_hills.pop()
if current_height == reference_height:
reference_cost += 1
pairs += reference_cost
else:
pairs += 1
reference_hills.append((reference_height, reference_cost))
reference_height = current_height
reference_cost = 1
reference_hills.append((reference_height, reference_cost))
start = 1 if reference_hills[0][1] else 2
pairs += sum(reference_hills[i][1] for i in range(start, len(reference_hills)))
print(pairs)
```
Yes
| 84,621 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Everyone knows that long ago on the territory of present-day Berland there lived Bindian tribes. Their capital was surrounded by n hills, forming a circle. On each hill there was a watchman, who watched the neighbourhood day and night.
In case of any danger the watchman could make a fire on the hill. One watchman could see the signal of another watchman, if on the circle arc connecting the two hills there was no hill higher than any of the two. As for any two hills there are two different circle arcs connecting them, the signal was seen if the above mentioned condition was satisfied on at least one of the arcs. For example, for any two neighbouring watchmen it is true that the signal of one will be seen by the other.
An important characteristics of this watch system was the amount of pairs of watchmen able to see each other's signals. You are to find this amount by the given heights of the hills.
Input
The first line of the input data contains an integer number n (3 β€ n β€ 106), n β the amount of hills around the capital. The second line contains n numbers β heights of the hills in clockwise order. All height numbers are integer and lie between 1 and 109.
Output
Print the required amount of pairs.
Examples
Input
5
1 2 4 5 3
Output
7
Submitted Solution:
```
from sys import stdin, stdout
def rotate(a):
mx = -1
mxp = -1;
for i in range(len(a)):
if a[i] > mx:
mx = a[i]
mxp = i
n = len(a)
h = [0]*n
#print(mxp)
for i in range(mxp, mxp + n):
h[i-mxp] = a[i%n]
h.append(h[0])
return h
def gettotalpairs(n, a):
h = rotate(a)
l = [0]*len(h)
r = [0]*len(h)
c = [0]*len(h)
l[0] = n
for i in range(1, n):
l[i] = i-1
while h[i] > h[l[i]]:
l[i] = l[l[i]]
if h[i] == h[l[i]]:
c[i] = c[l[i]]+1
l[i] = l[l[i]]
r[n] = n
for i in range(n-1, -1, -1):
r[i] = i + 1
while h[i] > h[r[i]]:
r[i] = r[r[i]]
if h[i] == h[r[i]]:
r[i] = r[r[i]]
res = 0
for i in range(n):
if h[i] < h[0]:
if l[i] == 0 and r[i] == n:
res += 1;
else:
res += 2
res += c[i];
return int(res)
if __name__ == '__main__':
n = int(stdin.readline())
a = list(map(int, stdin.readline().split()))
res = gettotalpairs(n, a)
stdout.write(str(res))
```
Yes
| 84,622 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Everyone knows that long ago on the territory of present-day Berland there lived Bindian tribes. Their capital was surrounded by n hills, forming a circle. On each hill there was a watchman, who watched the neighbourhood day and night.
In case of any danger the watchman could make a fire on the hill. One watchman could see the signal of another watchman, if on the circle arc connecting the two hills there was no hill higher than any of the two. As for any two hills there are two different circle arcs connecting them, the signal was seen if the above mentioned condition was satisfied on at least one of the arcs. For example, for any two neighbouring watchmen it is true that the signal of one will be seen by the other.
An important characteristics of this watch system was the amount of pairs of watchmen able to see each other's signals. You are to find this amount by the given heights of the hills.
Input
The first line of the input data contains an integer number n (3 β€ n β€ 106), n β the amount of hills around the capital. The second line contains n numbers β heights of the hills in clockwise order. All height numbers are integer and lie between 1 and 109.
Output
Print the required amount of pairs.
Examples
Input
5
1 2 4 5 3
Output
7
Submitted Solution:
```
t,n=int(input()),tuple(map(int,input().split()))
if t<2:print(0)
mx=ans=0
c=1
for i in range(1,len(n)):
if n[i]>n[mx]:
ans+=i
mx=i
c=1
elif n[i]<n[mx]:
ans+=i-mx+c-1
else:
ans+=i-mx+c-1 if c>1 else i
mx=i
c+=1
print(ans)
```
No
| 84,623 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Everyone knows that long ago on the territory of present-day Berland there lived Bindian tribes. Their capital was surrounded by n hills, forming a circle. On each hill there was a watchman, who watched the neighbourhood day and night.
In case of any danger the watchman could make a fire on the hill. One watchman could see the signal of another watchman, if on the circle arc connecting the two hills there was no hill higher than any of the two. As for any two hills there are two different circle arcs connecting them, the signal was seen if the above mentioned condition was satisfied on at least one of the arcs. For example, for any two neighbouring watchmen it is true that the signal of one will be seen by the other.
An important characteristics of this watch system was the amount of pairs of watchmen able to see each other's signals. You are to find this amount by the given heights of the hills.
Input
The first line of the input data contains an integer number n (3 β€ n β€ 106), n β the amount of hills around the capital. The second line contains n numbers β heights of the hills in clockwise order. All height numbers are integer and lie between 1 and 109.
Output
Print the required amount of pairs.
Examples
Input
5
1 2 4 5 3
Output
7
Submitted Solution:
```
n = int(input())
test = dict()
arr = list(map(int, input().split())) * 2
answ = n
for i in range(n):
loc_max = 0
for j in range(i + 2, i + n - 1):
if j >= n and i in test and j % n in test[i]:
break
loc_max = max(loc_max, arr[j - 1])
if loc_max <= min(arr[i], arr[j]):
answ += 1
if i < n and j < n:
test[j] = dict()
test[j][i] = True
print(answ)
```
No
| 84,624 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Everyone knows that long ago on the territory of present-day Berland there lived Bindian tribes. Their capital was surrounded by n hills, forming a circle. On each hill there was a watchman, who watched the neighbourhood day and night.
In case of any danger the watchman could make a fire on the hill. One watchman could see the signal of another watchman, if on the circle arc connecting the two hills there was no hill higher than any of the two. As for any two hills there are two different circle arcs connecting them, the signal was seen if the above mentioned condition was satisfied on at least one of the arcs. For example, for any two neighbouring watchmen it is true that the signal of one will be seen by the other.
An important characteristics of this watch system was the amount of pairs of watchmen able to see each other's signals. You are to find this amount by the given heights of the hills.
Input
The first line of the input data contains an integer number n (3 β€ n β€ 106), n β the amount of hills around the capital. The second line contains n numbers β heights of the hills in clockwise order. All height numbers are integer and lie between 1 and 109.
Output
Print the required amount of pairs.
Examples
Input
5
1 2 4 5 3
Output
7
Submitted Solution:
```
n = int(input())
arr = list(map(int, input().split()))
left_max = [0 for i in range(0, n)]
right_max = [0 for i in range(0, n)]
for i in range(1, n):
left_max[i] = max(left_max[i - 1], arr[i - 1])
for i in range(n - 2, -1, -1):
right_max[i] = max(right_max[i + 1], arr[i + 1])
right_idx = [n for i in range(0, n)]
for i in range(0, n):
for j in range(i + 1, n):
if arr[j] > arr[i]:
right_idx[i] = j
break
cnt = 0
for i in range(0, n):
for j in range(i + 1, n):
a, b = arr[i], arr[j]
if a >= left_max[i] and a >= right_max[j] and b >= left_max[i] and b >= right_max[j]:
cnt += 1
elif right_idx[i] >= j:
cnt += 1
print(cnt)
```
No
| 84,625 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Everyone knows that long ago on the territory of present-day Berland there lived Bindian tribes. Their capital was surrounded by n hills, forming a circle. On each hill there was a watchman, who watched the neighbourhood day and night.
In case of any danger the watchman could make a fire on the hill. One watchman could see the signal of another watchman, if on the circle arc connecting the two hills there was no hill higher than any of the two. As for any two hills there are two different circle arcs connecting them, the signal was seen if the above mentioned condition was satisfied on at least one of the arcs. For example, for any two neighbouring watchmen it is true that the signal of one will be seen by the other.
An important characteristics of this watch system was the amount of pairs of watchmen able to see each other's signals. You are to find this amount by the given heights of the hills.
Input
The first line of the input data contains an integer number n (3 β€ n β€ 106), n β the amount of hills around the capital. The second line contains n numbers β heights of the hills in clockwise order. All height numbers are integer and lie between 1 and 109.
Output
Print the required amount of pairs.
Examples
Input
5
1 2 4 5 3
Output
7
Submitted Solution:
```
n = int(input())
test = [[False for _ in range(n)] for _ in range(n)]
arr = list(map(int, input().split())) * 2
answ = n
for i in range(n):
loc_max = 0
for j in range(i + 2, i + n - 1):
if test[i % n][j % n]:
break
loc_max = max(loc_max, arr[j - 1])
if loc_max <= min(arr[i], arr[j]):
answ += 1
test[i % n][j % n] = True
test[j % n][i % n] = True
print(answ)
```
No
| 84,626 |
Provide tags and a correct Python 3 solution for this coding contest problem.
You are given array a with n integers and m queries. The i-th query is given with three integers li, ri, xi.
For the i-th query find any position pi (li β€ pi β€ ri) so that api β xi.
Input
The first line contains two integers n, m (1 β€ n, m β€ 2Β·105) β the number of elements in a and the number of queries.
The second line contains n integers ai (1 β€ ai β€ 106) β the elements of the array a.
Each of the next m lines contains three integers li, ri, xi (1 β€ li β€ ri β€ n, 1 β€ xi β€ 106) β the parameters of the i-th query.
Output
Print m lines. On the i-th line print integer pi β the position of any number not equal to xi in segment [li, ri] or the value - 1 if there is no such number.
Examples
Input
6 4
1 2 1 1 3 5
1 4 1
2 6 2
3 4 1
3 4 2
Output
2
6
-1
4
Tags: data structures, implementation
Correct Solution:
```
from sys import stdin
_data = iter(stdin.read().split('\n'))
def input():
while True:
return next(_data)
n ,m = map(int, input().split())
a = list(map(int, input().split()))
ans=[]
difPre=[-1 for i in range(n)]
for i in range(1,n):
if a[i]==a[i-1]:
difPre[i]=difPre[i-1]
else:
difPre[i]=i-1
for i in range(m):
l,r,x=map(int,input().split())
if a[r-1]!=x:
ans.append(str(r))
else:
if difPre[r-1]>=l-1:
ans.append(str(difPre[r-1]+1))
else:
ans.append('-1')
print('\n'.join(ans))
```
| 84,627 |
Provide tags and a correct Python 3 solution for this coding contest problem.
You are given array a with n integers and m queries. The i-th query is given with three integers li, ri, xi.
For the i-th query find any position pi (li β€ pi β€ ri) so that api β xi.
Input
The first line contains two integers n, m (1 β€ n, m β€ 2Β·105) β the number of elements in a and the number of queries.
The second line contains n integers ai (1 β€ ai β€ 106) β the elements of the array a.
Each of the next m lines contains three integers li, ri, xi (1 β€ li β€ ri β€ n, 1 β€ xi β€ 106) β the parameters of the i-th query.
Output
Print m lines. On the i-th line print integer pi β the position of any number not equal to xi in segment [li, ri] or the value - 1 if there is no such number.
Examples
Input
6 4
1 2 1 1 3 5
1 4 1
2 6 2
3 4 1
3 4 2
Output
2
6
-1
4
Tags: data structures, implementation
Correct Solution:
```
import sys
input = sys.stdin.readline
n, m = map(int, input().split())
a = list(map(int, input().split()))
b, c = [0], []
now = 0
for j in range(n - 1):
if a[j] ^ a[j + 1]:
now += 1
c.append(j)
b.append(now)
c.append(n)
for _ in range(m):
l, r, p = map(int, input().split())
x = c[b[l - 1]]
y = x + 1
if a[l - 1] ^p:
ans = l
elif y >= r:
ans = -1
else:
ans = x + 1 if a[x] ^ p else y + 1
print(ans)
```
| 84,628 |
Provide tags and a correct Python 3 solution for this coding contest problem.
You are given array a with n integers and m queries. The i-th query is given with three integers li, ri, xi.
For the i-th query find any position pi (li β€ pi β€ ri) so that api β xi.
Input
The first line contains two integers n, m (1 β€ n, m β€ 2Β·105) β the number of elements in a and the number of queries.
The second line contains n integers ai (1 β€ ai β€ 106) β the elements of the array a.
Each of the next m lines contains three integers li, ri, xi (1 β€ li β€ ri β€ n, 1 β€ xi β€ 106) β the parameters of the i-th query.
Output
Print m lines. On the i-th line print integer pi β the position of any number not equal to xi in segment [li, ri] or the value - 1 if there is no such number.
Examples
Input
6 4
1 2 1 1 3 5
1 4 1
2 6 2
3 4 1
3 4 2
Output
2
6
-1
4
Tags: data structures, implementation
Correct Solution:
```
import collections
import math
n ,m = map(int, input().split())
A = list(map(int, input().split()))
ans, f = [], [0] * n
f[0] = -1
for i in range(1, n):
if A[i] != A[i - 1]:
f[i] = i - 1
else:
f[i] = f[i - 1]
for i in range(m):
l, r, x = map(int, input().split())
#q.append([l - 1, r - 1, x])
#for i in range(m):
if A[r - 1] != x:
ans.append(r)
elif f[r - 1] >= l - 1:
ans.append(f[r - 1] + 1)
else:
ans.append(-1)
print('\n'.join(str(x) for x in ans))
```
| 84,629 |
Provide tags and a correct Python 3 solution for this coding contest problem.
You are given array a with n integers and m queries. The i-th query is given with three integers li, ri, xi.
For the i-th query find any position pi (li β€ pi β€ ri) so that api β xi.
Input
The first line contains two integers n, m (1 β€ n, m β€ 2Β·105) β the number of elements in a and the number of queries.
The second line contains n integers ai (1 β€ ai β€ 106) β the elements of the array a.
Each of the next m lines contains three integers li, ri, xi (1 β€ li β€ ri β€ n, 1 β€ xi β€ 106) β the parameters of the i-th query.
Output
Print m lines. On the i-th line print integer pi β the position of any number not equal to xi in segment [li, ri] or the value - 1 if there is no such number.
Examples
Input
6 4
1 2 1 1 3 5
1 4 1
2 6 2
3 4 1
3 4 2
Output
2
6
-1
4
Tags: data structures, implementation
Correct Solution:
```
from itertools import combinations, accumulate, groupby, count
from sys import stdout, stdin, setrecursionlimit
from io import BytesIO, IOBase
from collections import *
from random import *
from bisect import *
from string import *
from queue import *
from heapq import *
from math import *
from os import *
from re import *
####################################---fast-input-output----#########################################
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 = read(self._fd, max(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 = read(self._fd, max(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:
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")
stdin, stdout = IOWrapper(stdin), IOWrapper(stdout)
def fast(): return stdin.readline().strip()
def zzz(): return [int(i) for i in fast().split()]
z, zz = input, lambda: list(map(int, z().split()))
szz, graph, mod, szzz = lambda: sorted(
zz()), {}, 10**9 + 7, lambda: sorted(zzz())
def lcd(xnum1, xnum2): return (xnum1 * xnum2 // gcd(xnum1, xnum2))
def print(answer, end='\n'): stdout.write(str(answer) + end)
dx = [-1, 1, 0, 0, 1, -1, 1, -1]
dy = [0, 0, 1, -1, 1, -1, -1, 1]
###########################---Some Rule For Me To Follow---#################################
"""
--instants of Reading problem continuously try to understand them.
--If you Know some , Then you probably don't know him !
"""
###########################---START-CODING---###############################################
# num = int(z())
# lst = []
# for _ in range(num):
# arr = zzz()
# lst.append(arr)
# left = 0
# right = 10**9 + 1
# while right - left > 1:
# curr = (right + left) // 2
# currSet = set()
# for i in range(num):
# msk = 0
# for j in range(5):
# if lst[i][j] >= curr:
# msk |= 1 << j
# currSet.add(msk)
# flag = False
# for x in currSet:
# for y in currSet:
# for k in currSet:
# if x | y | k == 31:
# flag = True
# if flag:
# left = curr
# else:
# right = curr
# print(left)
n, m = zzz()
arr = zzz()
new = [0] * (n + 1)
for i in range(n - 2, -1, -1):
if arr[i] == arr[i + 1]:
new[i] = new[i + 1]
else:
new[i] = i + 1
res = [0] * (m)
for _ in range(m):
l, r, x = zzz()
ans = -1
if arr[l - 1] != x:
ans = l
else:
if new[l - 1] != new[r - 1]:
ans = new[l - 1] + 1
res[_] = ans
for i in res:
print(i)
```
| 84,630 |
Provide tags and a correct Python 3 solution for this coding contest problem.
You are given array a with n integers and m queries. The i-th query is given with three integers li, ri, xi.
For the i-th query find any position pi (li β€ pi β€ ri) so that api β xi.
Input
The first line contains two integers n, m (1 β€ n, m β€ 2Β·105) β the number of elements in a and the number of queries.
The second line contains n integers ai (1 β€ ai β€ 106) β the elements of the array a.
Each of the next m lines contains three integers li, ri, xi (1 β€ li β€ ri β€ n, 1 β€ xi β€ 106) β the parameters of the i-th query.
Output
Print m lines. On the i-th line print integer pi β the position of any number not equal to xi in segment [li, ri] or the value - 1 if there is no such number.
Examples
Input
6 4
1 2 1 1 3 5
1 4 1
2 6 2
3 4 1
3 4 2
Output
2
6
-1
4
Tags: data structures, implementation
Correct Solution:
```
import sys
def preprocess(arr):
left_i = -1
prev = arr[0]
preprocessed = []
for i, k in enumerate(arr):
if prev != k:
prev = k
left_i = i
preprocessed.append(left_i)
return preprocessed
def query(arr, pre, l, r, x):
if arr[r-1] != x:
return r
if pre[r-1] >= l:
return pre[r-1]
return -1
def solve():
n, m = map(int, sys.stdin.readline().split())
arr = list(map(int, sys.stdin.readline().split()))
pre = preprocess(arr)
for _ in range(m):
l, r, x = map(int, sys.stdin.readline().split())
yield str(query(arr, pre, l, r, x))
def main():
sys.stdout.write("\n".join(solve()))
main()
```
| 84,631 |
Provide tags and a correct Python 3 solution for this coding contest problem.
You are given array a with n integers and m queries. The i-th query is given with three integers li, ri, xi.
For the i-th query find any position pi (li β€ pi β€ ri) so that api β xi.
Input
The first line contains two integers n, m (1 β€ n, m β€ 2Β·105) β the number of elements in a and the number of queries.
The second line contains n integers ai (1 β€ ai β€ 106) β the elements of the array a.
Each of the next m lines contains three integers li, ri, xi (1 β€ li β€ ri β€ n, 1 β€ xi β€ 106) β the parameters of the i-th query.
Output
Print m lines. On the i-th line print integer pi β the position of any number not equal to xi in segment [li, ri] or the value - 1 if there is no such number.
Examples
Input
6 4
1 2 1 1 3 5
1 4 1
2 6 2
3 4 1
3 4 2
Output
2
6
-1
4
Tags: data structures, implementation
Correct Solution:
```
from sys import *
n, m = [int(t) for t in input().split()]
vec = [0 for t in range(n)]
pre = [0 for t in range(n)]
for idx, val in enumerate([int(t) for t in stdin.readline().split()]):
vec[idx] = val
pre[idx] = -1 if idx == 0 else (idx-1 if vec[idx-1] != val else pre[idx-1])
ans = [0 for t in range(m)]
for q in range(m):
l, r, x = [int(t) for t in stdin.readline().split()]
l -= 1
r -= 1
if vec[l] == x and vec[r] == x:
ans[q] = (-1 if pre[r] < l else pre[r]+1)
else:
ans[q] = (l+1 if vec[l] != x else r+1)
print("\n".join([str(t) for t in ans]))
```
| 84,632 |
Provide tags and a correct Python 3 solution for this coding contest problem.
You are given array a with n integers and m queries. The i-th query is given with three integers li, ri, xi.
For the i-th query find any position pi (li β€ pi β€ ri) so that api β xi.
Input
The first line contains two integers n, m (1 β€ n, m β€ 2Β·105) β the number of elements in a and the number of queries.
The second line contains n integers ai (1 β€ ai β€ 106) β the elements of the array a.
Each of the next m lines contains three integers li, ri, xi (1 β€ li β€ ri β€ n, 1 β€ xi β€ 106) β the parameters of the i-th query.
Output
Print m lines. On the i-th line print integer pi β the position of any number not equal to xi in segment [li, ri] or the value - 1 if there is no such number.
Examples
Input
6 4
1 2 1 1 3 5
1 4 1
2 6 2
3 4 1
3 4 2
Output
2
6
-1
4
Tags: data structures, implementation
Correct Solution:
```
from collections import defaultdict
import bisect
from itertools import accumulate
import os
import sys
import math
from decimal import *
from io import BytesIO, IOBase
BUFSIZE = 8192
class FastIO(IOBase):
newlines = 0
def __init__(self, file):
self._fd = file.fileno()
self.buffer = BytesIO()
self.writable = "x" in file.mode or "r" not in file.mode
self.write = self.buffer.write if self.writable else None
def read(self):
while True:
b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
if not b:
break
ptr = self.buffer.tell()
self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr)
self.newlines = 0
return self.buffer.read()
def readline(self):
while self.newlines == 0:
b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
self.newlines = b.count(b"\n") + (not b)
ptr = self.buffer.tell()
self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr)
self.newlines -= 1
return self.buffer.readline()
def flush(self):
if self.writable:
os.write(self._fd, self.buffer.getvalue())
self.buffer.truncate(0), self.buffer.seek(0)
class IOWrapper(IOBase):
def __init__(self, file):
self.buffer = FastIO(file)
self.flush = self.buffer.flush
self.writable = self.buffer.writable
self.write = lambda s: self.buffer.write(s.encode("ascii"))
self.read = lambda: self.buffer.read().decode("ascii")
self.readline = lambda: self.buffer.readline().decode("ascii")
sys.stdin, sys.stdout = IOWrapper(sys.stdin), IOWrapper(sys.stdout)
def input(): return sys.stdin.readline().rstrip("\r\n")
# ------------------- fast io --------------------]]
n,m=map(int,input().split())
a=list(map(int,input().split()))
b=[]
for i in range(n):
if i==0 or a[i]!=a[i-1]:
b.append(i)
else:
b.append(b[i-1])
ans=[]
for i in range(m):
l,r,x=map(int,input().split())
ans.append(r if a[r-1]!=x else (b[r-1] if b[r-1]>=l else -1))
print('\n'.join(map(str,ans)))
```
| 84,633 |
Provide tags and a correct Python 3 solution for this coding contest problem.
You are given array a with n integers and m queries. The i-th query is given with three integers li, ri, xi.
For the i-th query find any position pi (li β€ pi β€ ri) so that api β xi.
Input
The first line contains two integers n, m (1 β€ n, m β€ 2Β·105) β the number of elements in a and the number of queries.
The second line contains n integers ai (1 β€ ai β€ 106) β the elements of the array a.
Each of the next m lines contains three integers li, ri, xi (1 β€ li β€ ri β€ n, 1 β€ xi β€ 106) β the parameters of the i-th query.
Output
Print m lines. On the i-th line print integer pi β the position of any number not equal to xi in segment [li, ri] or the value - 1 if there is no such number.
Examples
Input
6 4
1 2 1 1 3 5
1 4 1
2 6 2
3 4 1
3 4 2
Output
2
6
-1
4
Tags: data structures, implementation
Correct Solution:
```
from sys import *
n, m = [int(t) for t in input().split()]
vec = []
pre = []
for idx, val in enumerate([int(t) for t in stdin.readline().split()]):
vec.append(val)
last = -1 if idx == 0 else (idx-1 if vec[idx-1] != val else pre[idx-1])
pre.append(last)
ans = []
for q in range(m):
l, r, x = [int(t) for t in stdin.readline().split()]
l -= 1
r -= 1
if vec[l] == x and vec[r] == x:
ans.append(str(-1 if pre[r] < l else pre[r]+1))
else:
ans.append(str(l+1 if vec[l] != x else r+1))
print("\n".join(ans))
# PYPY !!
```
| 84,634 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
You are given array a with n integers and m queries. The i-th query is given with three integers li, ri, xi.
For the i-th query find any position pi (li β€ pi β€ ri) so that api β xi.
Input
The first line contains two integers n, m (1 β€ n, m β€ 2Β·105) β the number of elements in a and the number of queries.
The second line contains n integers ai (1 β€ ai β€ 106) β the elements of the array a.
Each of the next m lines contains three integers li, ri, xi (1 β€ li β€ ri β€ n, 1 β€ xi β€ 106) β the parameters of the i-th query.
Output
Print m lines. On the i-th line print integer pi β the position of any number not equal to xi in segment [li, ri] or the value - 1 if there is no such number.
Examples
Input
6 4
1 2 1 1 3 5
1 4 1
2 6 2
3 4 1
3 4 2
Output
2
6
-1
4
Submitted Solution:
```
from sys import stdin
n,m = [int(i) for i in stdin.readline().split()]
a = [int(i) for i in stdin.readline().split()]
b = [None] * n
b[0] = -1
ans = [None] * m
for i in range(1,len(a)):
if a[i] == a[i - 1]:
b[i] = b[i - 1]
else:
b[i] = i - 1
for i in range(m):
l,r,x = [int(j) for j in stdin.readline().split()]
k = r - 1
if a[k] != x:
ans[i] = str(k + 1)
elif b[k] + 1 >= l:
ans[i] = str(b[k] + 1)
else:
ans[i] = ('-1')
print('\n'.join(ans))
```
Yes
| 84,635 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
You are given array a with n integers and m queries. The i-th query is given with three integers li, ri, xi.
For the i-th query find any position pi (li β€ pi β€ ri) so that api β xi.
Input
The first line contains two integers n, m (1 β€ n, m β€ 2Β·105) β the number of elements in a and the number of queries.
The second line contains n integers ai (1 β€ ai β€ 106) β the elements of the array a.
Each of the next m lines contains three integers li, ri, xi (1 β€ li β€ ri β€ n, 1 β€ xi β€ 106) β the parameters of the i-th query.
Output
Print m lines. On the i-th line print integer pi β the position of any number not equal to xi in segment [li, ri] or the value - 1 if there is no such number.
Examples
Input
6 4
1 2 1 1 3 5
1 4 1
2 6 2
3 4 1
3 4 2
Output
2
6
-1
4
Submitted Solution:
```
from sys import *
def input():
return stdin.readline()
n ,m = map(int, input().split())
a = list(map(int, input().split()))
ans=[]
difPre=[-1 for i in range(n)]
for i in range(1,n):
if a[i]==a[i-1]:
difPre[i]=difPre[i-1]
else:
difPre[i]=i-1
for i in range(m):
l,r,x=map(int,input().split())
if a[r-1]!=x:
ans.append(str(r))
else:
if difPre[r-1]>=l-1:
ans.append(str(difPre[r-1]+1))
else:
ans.append('-1')
print('\n'.join(ans))
```
Yes
| 84,636 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
You are given array a with n integers and m queries. The i-th query is given with three integers li, ri, xi.
For the i-th query find any position pi (li β€ pi β€ ri) so that api β xi.
Input
The first line contains two integers n, m (1 β€ n, m β€ 2Β·105) β the number of elements in a and the number of queries.
The second line contains n integers ai (1 β€ ai β€ 106) β the elements of the array a.
Each of the next m lines contains three integers li, ri, xi (1 β€ li β€ ri β€ n, 1 β€ xi β€ 106) β the parameters of the i-th query.
Output
Print m lines. On the i-th line print integer pi β the position of any number not equal to xi in segment [li, ri] or the value - 1 if there is no such number.
Examples
Input
6 4
1 2 1 1 3 5
1 4 1
2 6 2
3 4 1
3 4 2
Output
2
6
-1
4
Submitted Solution:
```
n,m = [int(i) for i in input().split()]
a = input().split()
result = []
prev = [-1]*n
for i in range(1,n):
if a[i] != a[i-1]:
prev[i] = i-1
else:
prev[i] = prev[i-1]
for i in range(m):
l,r,x = input().split()
r = int(r)
if a[r-1] != x:
answer = r
elif prev[r-1]<int(l)-1:
answer = -1
else:
answer = prev[r-1]+1
result.append(str(answer))
print('\n' .join(result))
```
Yes
| 84,637 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
You are given array a with n integers and m queries. The i-th query is given with three integers li, ri, xi.
For the i-th query find any position pi (li β€ pi β€ ri) so that api β xi.
Input
The first line contains two integers n, m (1 β€ n, m β€ 2Β·105) β the number of elements in a and the number of queries.
The second line contains n integers ai (1 β€ ai β€ 106) β the elements of the array a.
Each of the next m lines contains three integers li, ri, xi (1 β€ li β€ ri β€ n, 1 β€ xi β€ 106) β the parameters of the i-th query.
Output
Print m lines. On the i-th line print integer pi β the position of any number not equal to xi in segment [li, ri] or the value - 1 if there is no such number.
Examples
Input
6 4
1 2 1 1 3 5
1 4 1
2 6 2
3 4 1
3 4 2
Output
2
6
-1
4
Submitted Solution:
```
n,m=map(int,input().split())
a=list(map(int,input().split()))
b=[]
for i in range(n):
if i==0 or a[i]!=a[i-1]:
b.append(i)
else:
b.append(b[i-1])
ans=[]
for i in range(m):
l,r,x=map(int,input().split())
ans.append(r if a[r-1]!=x else (b[r-1] if b[r-1]>=l else -1))
print('\n'.join(map(str,ans)))
```
Yes
| 84,638 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
You are given array a with n integers and m queries. The i-th query is given with three integers li, ri, xi.
For the i-th query find any position pi (li β€ pi β€ ri) so that api β xi.
Input
The first line contains two integers n, m (1 β€ n, m β€ 2Β·105) β the number of elements in a and the number of queries.
The second line contains n integers ai (1 β€ ai β€ 106) β the elements of the array a.
Each of the next m lines contains three integers li, ri, xi (1 β€ li β€ ri β€ n, 1 β€ xi β€ 106) β the parameters of the i-th query.
Output
Print m lines. On the i-th line print integer pi β the position of any number not equal to xi in segment [li, ri] or the value - 1 if there is no such number.
Examples
Input
6 4
1 2 1 1 3 5
1 4 1
2 6 2
3 4 1
3 4 2
Output
2
6
-1
4
Submitted Solution:
```
# -*- coding: utf-8 -*-
"""
Created on Tue May 17 15:26:55 2016
@author: Alex
"""
n,m = map(int,input().split())
l = list(map(int,input().split()))
leng = len(l)
prev = [-1 for i in range(n)]
for i in range(n-1):
if l[i] != l[i+1]:
prev[i+1] = i
else:
prev[i+1] = prev[i]
for i in range(m):
b = False
le,ri,xi = map(int,input().split())
if l[ri-1]!=xi:
print(ri)
elif prev[ri-1]<=le-1:
print(-1)
else:
print(prev[ri-1]+1)
```
No
| 84,639 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
You are given array a with n integers and m queries. The i-th query is given with three integers li, ri, xi.
For the i-th query find any position pi (li β€ pi β€ ri) so that api β xi.
Input
The first line contains two integers n, m (1 β€ n, m β€ 2Β·105) β the number of elements in a and the number of queries.
The second line contains n integers ai (1 β€ ai β€ 106) β the elements of the array a.
Each of the next m lines contains three integers li, ri, xi (1 β€ li β€ ri β€ n, 1 β€ xi β€ 106) β the parameters of the i-th query.
Output
Print m lines. On the i-th line print integer pi β the position of any number not equal to xi in segment [li, ri] or the value - 1 if there is no such number.
Examples
Input
6 4
1 2 1 1 3 5
1 4 1
2 6 2
3 4 1
3 4 2
Output
2
6
-1
4
Submitted Solution:
```
n,m = [int(i) for i in input().split()]
a = [int(i) for i in input().split()]
b = [-1]
ans = []
for i in range(1,len(a)):
if a[i] == a[i - 1]:
b.append(b[i - 1])
else:
b.append(i - 1)
for i in range(m):
l,r,x = [int(j) for j in input().split()]
k = r - 1
while b[k] != -1 and k >= l - 1:
if a[k] != x:
ans.append(k + 1)
break
k = b[k]
if len(ans) < i + 1:
ans.append(-1)
print(*ans, sep = '\n')
```
No
| 84,640 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
You are given array a with n integers and m queries. The i-th query is given with three integers li, ri, xi.
For the i-th query find any position pi (li β€ pi β€ ri) so that api β xi.
Input
The first line contains two integers n, m (1 β€ n, m β€ 2Β·105) β the number of elements in a and the number of queries.
The second line contains n integers ai (1 β€ ai β€ 106) β the elements of the array a.
Each of the next m lines contains three integers li, ri, xi (1 β€ li β€ ri β€ n, 1 β€ xi β€ 106) β the parameters of the i-th query.
Output
Print m lines. On the i-th line print integer pi β the position of any number not equal to xi in segment [li, ri] or the value - 1 if there is no such number.
Examples
Input
6 4
1 2 1 1 3 5
1 4 1
2 6 2
3 4 1
3 4 2
Output
2
6
-1
4
Submitted Solution:
```
from sys import stdin, stdout
from collections import defaultdict
cin = stdin.readline
cout = stdout.write
mp = lambda:list(map(int, cin().split()))
def binSearch(p, q, x):
low = p
high = q
while low<=high:
mid = (low+high)//2
dif = mid-low
if not dif:
if d[x][low+1]-d[x][low] > 1:
#print(2)
return d[x][low]+1
else:
#print(d[x][high])
return d[x][low]-1
elif d[x][mid] == d[x][low]+dif:
low = mid+1
else:
high = mid-1
n, m = mp()
a = mp()
d = defaultdict(list)
for i in range(n):
d[a[i]].append(i+1)
for _ in range(m):
l, r, x = mp()
if l in d[x]:
y = d[x].index(l)
else:
cout(str(l)+'\n')
continue
ind = y + r-l
if len(d[x])>ind and d[x][ind] == r:
cout('-1\n')
else:
if len(d[x])==1:
cout(str(r)+'\n')
else:
pos = binSearch(y, min(ind, len(d[x])-1), x)
cout(str(pos) + '\n')
```
No
| 84,641 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
You are given array a with n integers and m queries. The i-th query is given with three integers li, ri, xi.
For the i-th query find any position pi (li β€ pi β€ ri) so that api β xi.
Input
The first line contains two integers n, m (1 β€ n, m β€ 2Β·105) β the number of elements in a and the number of queries.
The second line contains n integers ai (1 β€ ai β€ 106) β the elements of the array a.
Each of the next m lines contains three integers li, ri, xi (1 β€ li β€ ri β€ n, 1 β€ xi β€ 106) β the parameters of the i-th query.
Output
Print m lines. On the i-th line print integer pi β the position of any number not equal to xi in segment [li, ri] or the value - 1 if there is no such number.
Examples
Input
6 4
1 2 1 1 3 5
1 4 1
2 6 2
3 4 1
3 4 2
Output
2
6
-1
4
Submitted Solution:
```
import sys
from random import randint
def work(ind,n):
for i in range(1,n):
if a[i] == a[i-1]:
ind[i] = ind[i-1]
else:
ind[i] = i-1
return ind
def work1(ind,answer):
q = sys.stdin.readline().split(' ')#input().split(' ')
#p = [randint(0,n),randint(0,n)]
#q = [min(p),max(p),randint(0,int(1e6))]
l = int(q[0])-1
r = int(q[1])-1
x = int(q[2])
if x == a[r]:
if ind[r]>=l:
#print(ind[r]+1)
#answer+= str(ind[r]+1)+' '
print(str(ind[r]+1)+' ')
else:
print(-1)
#answer+= '-1 '
else:
#print(int(r)+1)
#answer+= str(ind[r]+1)+' '
print(str(ind[r]+1)+' ')
return answer
n = sys.stdin.readline().split(' ')#input().split(' ')
m = int(n[1])
n = int(n[0])
a = [int(k) for k in sys.stdin.readline().split(' ')]
#n = int(2e5)
#m = int(2e5)
#a = [randint(0,int(1e6+1)) for i in range(n)]
ind = work(ind =[-1]*n,n = n)
answer=''
for i in range(m):
answer = work1(ind,answer)
print(answer)
#10 1
#1 2 2 2 2 1 1 2 1 1
#4 9 1
```
No
| 84,642 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
There are n bears in the inn and p places to sleep. Bears will party together for some number of nights (and days).
Bears love drinking juice. They don't like wine but they can't distinguish it from juice by taste or smell.
A bear doesn't sleep unless he drinks wine. A bear must go to sleep a few hours after drinking a wine. He will wake up many days after the party is over.
Radewoosh is the owner of the inn. He wants to put some number of barrels in front of bears. One barrel will contain wine and all other ones will contain juice. Radewoosh will challenge bears to find a barrel with wine.
Each night, the following happens in this exact order:
1. Each bear must choose a (maybe empty) set of barrels. The same barrel may be chosen by many bears.
2. Each bear drinks a glass from each barrel he chose.
3. All bears who drink wine go to sleep (exactly those bears who chose a barrel with wine). They will wake up many days after the party is over. If there are not enough places to sleep then bears lose immediately.
At the end, if it's sure where wine is and there is at least one awake bear then bears win (unless they have lost before because of the number of places to sleep).
Radewoosh wants to allow bears to win. He considers q scenarios. In the i-th scenario the party will last for i nights. Then, let Ri denote the maximum number of barrels for which bears surely win if they behave optimally. Let's define <image>. Your task is to find <image>, where <image> denotes the exclusive or (also denoted as XOR).
Note that the same barrel may be chosen by many bears and all of them will go to sleep at once.
Input
The only line of the input contains three integers n, p and q (1 β€ n β€ 109, 1 β€ p β€ 130, 1 β€ q β€ 2 000 000) β the number of bears, the number of places to sleep and the number of scenarios, respectively.
Output
Print one integer, equal to <image>.
Examples
Input
5 1 3
Output
32
Input
1 100 4
Output
4
Input
3 2 1
Output
7
Input
100 100 100
Output
381863924
Note
In the first sample, there are 5 bears and only 1 place to sleep. We have R1 = 6, R2 = 11, R3 = 16 so the answer is <image>. Let's analyze the optimal strategy for scenario with 2 days. There are R2 = 11 barrels and 10 of them contain juice.
* In the first night, the i-th bear chooses a barrel i only.
* If one of the first 5 barrels contains wine then one bear goes to sleep. Then, bears win because they know where wine is and there is at least one awake bear.
* But let's say none of the first 5 barrels contains wine. In the second night, the i-th bear chooses a barrel 5 + i.
* If one of barrels 6 β 10 contains wine then one bear goes to sleep. And again, bears win in such a situation.
* If nobody went to sleep then wine is in a barrel 11.
In the second sample, there is only one bear. He should choose an empty set of barrels in each night. Otherwise, he would maybe get wine and bears would lose (because there must be at least one awake bear). So, for any number of days we have Ri = 1. The answer is <image>.
Submitted Solution:
```
print(1373452814)
```
No
| 84,643 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
There are n bears in the inn and p places to sleep. Bears will party together for some number of nights (and days).
Bears love drinking juice. They don't like wine but they can't distinguish it from juice by taste or smell.
A bear doesn't sleep unless he drinks wine. A bear must go to sleep a few hours after drinking a wine. He will wake up many days after the party is over.
Radewoosh is the owner of the inn. He wants to put some number of barrels in front of bears. One barrel will contain wine and all other ones will contain juice. Radewoosh will challenge bears to find a barrel with wine.
Each night, the following happens in this exact order:
1. Each bear must choose a (maybe empty) set of barrels. The same barrel may be chosen by many bears.
2. Each bear drinks a glass from each barrel he chose.
3. All bears who drink wine go to sleep (exactly those bears who chose a barrel with wine). They will wake up many days after the party is over. If there are not enough places to sleep then bears lose immediately.
At the end, if it's sure where wine is and there is at least one awake bear then bears win (unless they have lost before because of the number of places to sleep).
Radewoosh wants to allow bears to win. He considers q scenarios. In the i-th scenario the party will last for i nights. Then, let Ri denote the maximum number of barrels for which bears surely win if they behave optimally. Let's define <image>. Your task is to find <image>, where <image> denotes the exclusive or (also denoted as XOR).
Note that the same barrel may be chosen by many bears and all of them will go to sleep at once.
Input
The only line of the input contains three integers n, p and q (1 β€ n β€ 109, 1 β€ p β€ 130, 1 β€ q β€ 2 000 000) β the number of bears, the number of places to sleep and the number of scenarios, respectively.
Output
Print one integer, equal to <image>.
Examples
Input
5 1 3
Output
32
Input
1 100 4
Output
4
Input
3 2 1
Output
7
Input
100 100 100
Output
381863924
Note
In the first sample, there are 5 bears and only 1 place to sleep. We have R1 = 6, R2 = 11, R3 = 16 so the answer is <image>. Let's analyze the optimal strategy for scenario with 2 days. There are R2 = 11 barrels and 10 of them contain juice.
* In the first night, the i-th bear chooses a barrel i only.
* If one of the first 5 barrels contains wine then one bear goes to sleep. Then, bears win because they know where wine is and there is at least one awake bear.
* But let's say none of the first 5 barrels contains wine. In the second night, the i-th bear chooses a barrel 5 + i.
* If one of barrels 6 β 10 contains wine then one bear goes to sleep. And again, bears win in such a situation.
* If nobody went to sleep then wine is in a barrel 11.
In the second sample, there is only one bear. He should choose an empty set of barrels in each night. Otherwise, he would maybe get wine and bears would lose (because there must be at least one awake bear). So, for any number of days we have Ri = 1. The answer is <image>.
Submitted Solution:
```
mod=2<<32
def C(m,n):
tmp=1
for i in range(m-n+1,m+1):
tmp=tmp*i
pass
for i in range(1,n+1):
tmp=tmp//i
pass
return tmp%mod
pass
n,p,r=map(int,input().split())
ans=0
for i in range(1,r+1):
tot=0
for j in range(0,min(n-1,p)+1):
tot=(tot+C(n,j)*(i**j)%mod)%mod;
ans=((tot*i)%mod)^ans
pass
print(ans)
```
No
| 84,644 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
There are n bears in the inn and p places to sleep. Bears will party together for some number of nights (and days).
Bears love drinking juice. They don't like wine but they can't distinguish it from juice by taste or smell.
A bear doesn't sleep unless he drinks wine. A bear must go to sleep a few hours after drinking a wine. He will wake up many days after the party is over.
Radewoosh is the owner of the inn. He wants to put some number of barrels in front of bears. One barrel will contain wine and all other ones will contain juice. Radewoosh will challenge bears to find a barrel with wine.
Each night, the following happens in this exact order:
1. Each bear must choose a (maybe empty) set of barrels. The same barrel may be chosen by many bears.
2. Each bear drinks a glass from each barrel he chose.
3. All bears who drink wine go to sleep (exactly those bears who chose a barrel with wine). They will wake up many days after the party is over. If there are not enough places to sleep then bears lose immediately.
At the end, if it's sure where wine is and there is at least one awake bear then bears win (unless they have lost before because of the number of places to sleep).
Radewoosh wants to allow bears to win. He considers q scenarios. In the i-th scenario the party will last for i nights. Then, let Ri denote the maximum number of barrels for which bears surely win if they behave optimally. Let's define <image>. Your task is to find <image>, where <image> denotes the exclusive or (also denoted as XOR).
Note that the same barrel may be chosen by many bears and all of them will go to sleep at once.
Input
The only line of the input contains three integers n, p and q (1 β€ n β€ 109, 1 β€ p β€ 130, 1 β€ q β€ 2 000 000) β the number of bears, the number of places to sleep and the number of scenarios, respectively.
Output
Print one integer, equal to <image>.
Examples
Input
5 1 3
Output
32
Input
1 100 4
Output
4
Input
3 2 1
Output
7
Input
100 100 100
Output
381863924
Note
In the first sample, there are 5 bears and only 1 place to sleep. We have R1 = 6, R2 = 11, R3 = 16 so the answer is <image>. Let's analyze the optimal strategy for scenario with 2 days. There are R2 = 11 barrels and 10 of them contain juice.
* In the first night, the i-th bear chooses a barrel i only.
* If one of the first 5 barrels contains wine then one bear goes to sleep. Then, bears win because they know where wine is and there is at least one awake bear.
* But let's say none of the first 5 barrels contains wine. In the second night, the i-th bear chooses a barrel 5 + i.
* If one of barrels 6 β 10 contains wine then one bear goes to sleep. And again, bears win in such a situation.
* If nobody went to sleep then wine is in a barrel 11.
In the second sample, there is only one bear. He should choose an empty set of barrels in each night. Otherwise, he would maybe get wine and bears would lose (because there must be at least one awake bear). So, for any number of days we have Ri = 1. The answer is <image>.
Submitted Solution:
```
MAX_P = 140
MD = (1 << 33) - 1
n, p, q = map(int, input().split())
n_prod = [1 for i in range(MAX_P)]
for i in range(1, MAX_P):
n_prod[i] = n_prod[i-1] * (n - i + 1)
fact = [max(i,1) for i in range(0, MAX_P+1)]
for i in range(1, MAX_P+1):
fact[i] *= fact[i-1]
def calc_ncr(r:int) -> int:
return (n_prod[r] // fact[r]) & MD
ncr = [calc_ncr(i) for i in range(MAX_P)]
x = 0
m = min(p, n-1)
for i in range(1, q+1):
s = 0
pw = 1
for j in range(0, m+1):
s += ncr[j] * pw
pw = (pw * i) & MD
x ^= (i*s) & MD
print(x)
```
No
| 84,645 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Recently Polycarp started to develop a text editor that works only with correct bracket sequences (abbreviated as CBS).
Note that a bracket sequence is correct if it is possible to get a correct mathematical expression by adding "+"-s and "1"-s to it. For example, sequences "(())()", "()" and "(()(()))" are correct, while ")(", "(()" and "(()))(" are not. Each bracket in CBS has a pair. For example, in "(()(()))":
* 1st bracket is paired with 8th,
* 2d bracket is paired with 3d,
* 3d bracket is paired with 2d,
* 4th bracket is paired with 7th,
* 5th bracket is paired with 6th,
* 6th bracket is paired with 5th,
* 7th bracket is paired with 4th,
* 8th bracket is paired with 1st.
Polycarp's editor currently supports only three operations during the use of CBS. The cursor in the editor takes the whole position of one of the brackets (not the position between the brackets!). There are three operations being supported:
* Β«LΒ» β move the cursor one position to the left,
* Β«RΒ» β move the cursor one position to the right,
* Β«DΒ» β delete the bracket in which the cursor is located, delete the bracket it's paired to and all brackets between them (that is, delete a substring between the bracket in which the cursor is located and the one it's paired to).
After the operation "D" the cursor moves to the nearest bracket to the right (of course, among the non-deleted). If there is no such bracket (that is, the suffix of the CBS was deleted), then the cursor moves to the nearest bracket to the left (of course, among the non-deleted).
There are pictures illustrated several usages of operation "D" below.
<image>
All incorrect operations (shift cursor over the end of CBS, delete the whole CBS, etc.) are not supported by Polycarp's editor.
Polycarp is very proud of his development, can you implement the functionality of his editor?
Input
The first line contains three positive integers n, m and p (2 β€ n β€ 500 000, 1 β€ m β€ 500 000, 1 β€ p β€ n) β the number of brackets in the correct bracket sequence, the number of operations and the initial position of cursor. Positions in the sequence are numbered from left to right, starting from one. It is guaranteed that n is even.
It is followed by the string of n characters "(" and ")" forming the correct bracket sequence.
Then follow a string of m characters "L", "R" and "D" β a sequence of the operations. Operations are carried out one by one from the first to the last. It is guaranteed that the given operations never move the cursor outside the bracket sequence, as well as the fact that after all operations a bracket sequence will be non-empty.
Output
Print the correct bracket sequence, obtained as a result of applying all operations to the initial sequence.
Examples
Input
8 4 5
(())()()
RDLD
Output
()
Input
12 5 3
((()())(()))
RRDLD
Output
(()(()))
Input
8 8 8
(())()()
LLLLLLDD
Output
()()
Note
In the first sample the cursor is initially at position 5. Consider actions of the editor:
1. command "R" β the cursor moves to the position 6 on the right;
2. command "D" β the deletion of brackets from the position 5 to the position 6. After that CBS takes the form (())(), the cursor is at the position 5;
3. command "L" β the cursor moves to the position 4 on the left;
4. command "D" β the deletion of brackets from the position 1 to the position 4. After that CBS takes the form (), the cursor is at the position 1.
Thus, the answer is equal to ().
Tags: data structures, dsu, strings
Correct Solution:
```
import sys
sys.stderr = sys.stdout
from collections import deque
def brackets(n, m, p, B, S):
P = [i-1 for i in range(n+2)]
P[0] = None
Q = [i+1 for i in range(n+2)]
Q[n+1] = None
J = [None] * (n + 2)
D = deque()
for i, b in enumerate(B, 1):
if b == '(':
D.append(i)
elif b == ')':
j = D.pop()
J[i] = j
J[j] = i
i = p
for c in S:
if c == 'L':
i = P[i]
elif c == 'R':
i = Q[i]
else:
j = J[i]
if j < i:
i, j = j, i
Q[P[i]] = Q[j]
P[Q[j]] = P[i]
i = Q[j] if Q[j] <= n else P[i]
L = []
i = Q[0]
while i <= n:
L.append(B[i-1])
i = Q[i]
return L
def main():
n, m, p = readinti()
B = input()
S = input()
print(''.join(brackets(n, m, p, B, S)))
##########
def readint():
return int(input())
def readinti():
return map(int, input().split())
def readintt():
return tuple(readinti())
def readintl():
return list(readinti())
def readinttl(k):
return [readintt() for _ in range(k)]
def readintll(k):
return [readintl() for _ in range(k)]
def log(*args, **kwargs):
print(*args, **kwargs, file=sys.__stderr__)
if __name__ == '__main__':
main()
```
| 84,646 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Recently Polycarp started to develop a text editor that works only with correct bracket sequences (abbreviated as CBS).
Note that a bracket sequence is correct if it is possible to get a correct mathematical expression by adding "+"-s and "1"-s to it. For example, sequences "(())()", "()" and "(()(()))" are correct, while ")(", "(()" and "(()))(" are not. Each bracket in CBS has a pair. For example, in "(()(()))":
* 1st bracket is paired with 8th,
* 2d bracket is paired with 3d,
* 3d bracket is paired with 2d,
* 4th bracket is paired with 7th,
* 5th bracket is paired with 6th,
* 6th bracket is paired with 5th,
* 7th bracket is paired with 4th,
* 8th bracket is paired with 1st.
Polycarp's editor currently supports only three operations during the use of CBS. The cursor in the editor takes the whole position of one of the brackets (not the position between the brackets!). There are three operations being supported:
* Β«LΒ» β move the cursor one position to the left,
* Β«RΒ» β move the cursor one position to the right,
* Β«DΒ» β delete the bracket in which the cursor is located, delete the bracket it's paired to and all brackets between them (that is, delete a substring between the bracket in which the cursor is located and the one it's paired to).
After the operation "D" the cursor moves to the nearest bracket to the right (of course, among the non-deleted). If there is no such bracket (that is, the suffix of the CBS was deleted), then the cursor moves to the nearest bracket to the left (of course, among the non-deleted).
There are pictures illustrated several usages of operation "D" below.
<image>
All incorrect operations (shift cursor over the end of CBS, delete the whole CBS, etc.) are not supported by Polycarp's editor.
Polycarp is very proud of his development, can you implement the functionality of his editor?
Input
The first line contains three positive integers n, m and p (2 β€ n β€ 500 000, 1 β€ m β€ 500 000, 1 β€ p β€ n) β the number of brackets in the correct bracket sequence, the number of operations and the initial position of cursor. Positions in the sequence are numbered from left to right, starting from one. It is guaranteed that n is even.
It is followed by the string of n characters "(" and ")" forming the correct bracket sequence.
Then follow a string of m characters "L", "R" and "D" β a sequence of the operations. Operations are carried out one by one from the first to the last. It is guaranteed that the given operations never move the cursor outside the bracket sequence, as well as the fact that after all operations a bracket sequence will be non-empty.
Output
Print the correct bracket sequence, obtained as a result of applying all operations to the initial sequence.
Examples
Input
8 4 5
(())()()
RDLD
Output
()
Input
12 5 3
((()())(()))
RRDLD
Output
(()(()))
Input
8 8 8
(())()()
LLLLLLDD
Output
()()
Note
In the first sample the cursor is initially at position 5. Consider actions of the editor:
1. command "R" β the cursor moves to the position 6 on the right;
2. command "D" β the deletion of brackets from the position 5 to the position 6. After that CBS takes the form (())(), the cursor is at the position 5;
3. command "L" β the cursor moves to the position 4 on the left;
4. command "D" β the deletion of brackets from the position 1 to the position 4. After that CBS takes the form (), the cursor is at the position 1.
Thus, the answer is equal to ().
Tags: data structures, dsu, strings
Correct Solution:
```
def preproc(str, leng):
li = []
res = [-1]*leng
for i in range(leng):
if str[i] == '(':
li.append(i)
else:
start, end = li.pop(), i
res[start] = end
res[end] = start
return res
def delete(flags, cursor, pairs):
pos = pairs[cursor]
direction = 1 if pos > cursor else -1
while(pos+direction > 0 and pos+direction < len(flags) and flags[pos+direction] != -1):
pos = flags[pos+direction]
return pos
leng, op_num, cursor = map(int, input().strip().split())
cursor = cursor-1
str = input().strip()
ops = input().strip()
pairs = preproc(str, leng)
flags = [-1]*leng
#print(leng, op_num, cursor, str, ops, pairs)
for i in ops:
#print(i, cursor, flags)
if i == 'R' or i == 'L':
cursor = {
'R':(lambda cursor=cursor, flags=flags: cursor+1 if flags[cursor+1] == -1 else flags[cursor+1]+1),
'L':(lambda cursor=cursor, flags=flags: cursor-1 if flags[cursor-1] == -1 else flags[cursor-1]-1)
}[i]()
else:
delete_to = delete(flags, cursor, pairs)
delete_from = delete(flags, pairs[cursor], pairs)
flags[delete_from] = delete_to
flags[delete_to] = delete_from
cursor = max(delete_to, delete_from)
if cursor+1 < leng and flags[cursor+1] == -1:
cursor = cursor+1
elif cursor+1 < leng and flags[cursor+1] != -1 and flags[cursor+1]+1 < leng:
cursor = flags[cursor+1]+1
elif min(delete_from, delete_to) -1 > 0 and flags[min(delete_from, delete_to)-1] == -1:
cursor = min(delete_from, delete_to)-1
else:
cursor = flags[min(delete_from, delete_to)-1]-1
idx = 0
res = ''
while idx < leng:
if flags[idx] != -1:
idx = flags[idx]+1
continue
res += str[idx]
idx = idx+1
print(res)
```
| 84,647 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Recently Polycarp started to develop a text editor that works only with correct bracket sequences (abbreviated as CBS).
Note that a bracket sequence is correct if it is possible to get a correct mathematical expression by adding "+"-s and "1"-s to it. For example, sequences "(())()", "()" and "(()(()))" are correct, while ")(", "(()" and "(()))(" are not. Each bracket in CBS has a pair. For example, in "(()(()))":
* 1st bracket is paired with 8th,
* 2d bracket is paired with 3d,
* 3d bracket is paired with 2d,
* 4th bracket is paired with 7th,
* 5th bracket is paired with 6th,
* 6th bracket is paired with 5th,
* 7th bracket is paired with 4th,
* 8th bracket is paired with 1st.
Polycarp's editor currently supports only three operations during the use of CBS. The cursor in the editor takes the whole position of one of the brackets (not the position between the brackets!). There are three operations being supported:
* Β«LΒ» β move the cursor one position to the left,
* Β«RΒ» β move the cursor one position to the right,
* Β«DΒ» β delete the bracket in which the cursor is located, delete the bracket it's paired to and all brackets between them (that is, delete a substring between the bracket in which the cursor is located and the one it's paired to).
After the operation "D" the cursor moves to the nearest bracket to the right (of course, among the non-deleted). If there is no such bracket (that is, the suffix of the CBS was deleted), then the cursor moves to the nearest bracket to the left (of course, among the non-deleted).
There are pictures illustrated several usages of operation "D" below.
<image>
All incorrect operations (shift cursor over the end of CBS, delete the whole CBS, etc.) are not supported by Polycarp's editor.
Polycarp is very proud of his development, can you implement the functionality of his editor?
Input
The first line contains three positive integers n, m and p (2 β€ n β€ 500 000, 1 β€ m β€ 500 000, 1 β€ p β€ n) β the number of brackets in the correct bracket sequence, the number of operations and the initial position of cursor. Positions in the sequence are numbered from left to right, starting from one. It is guaranteed that n is even.
It is followed by the string of n characters "(" and ")" forming the correct bracket sequence.
Then follow a string of m characters "L", "R" and "D" β a sequence of the operations. Operations are carried out one by one from the first to the last. It is guaranteed that the given operations never move the cursor outside the bracket sequence, as well as the fact that after all operations a bracket sequence will be non-empty.
Output
Print the correct bracket sequence, obtained as a result of applying all operations to the initial sequence.
Examples
Input
8 4 5
(())()()
RDLD
Output
()
Input
12 5 3
((()())(()))
RRDLD
Output
(()(()))
Input
8 8 8
(())()()
LLLLLLDD
Output
()()
Note
In the first sample the cursor is initially at position 5. Consider actions of the editor:
1. command "R" β the cursor moves to the position 6 on the right;
2. command "D" β the deletion of brackets from the position 5 to the position 6. After that CBS takes the form (())(), the cursor is at the position 5;
3. command "L" β the cursor moves to the position 4 on the left;
4. command "D" β the deletion of brackets from the position 1 to the position 4. After that CBS takes the form (), the cursor is at the position 1.
Thus, the answer is equal to ().
Tags: data structures, dsu, strings
Correct Solution:
```
class Node:
def __init__(self, index):
self.left = index - 1
self.right = index + 1
self.pair = -1
if __name__ == "__main__":
n, m, p = map(int, input().split())
brackets = input()
operations = input()
nodes = [Node(i) for i in range(n + 1)]
stack = []
for i in range(n):
if brackets[i] == "(":
stack.append(i + 1)
else:
pair_id = stack.pop()
nodes[pair_id].pair = i + 1
nodes[i + 1].pair = pair_id
for i in range(m):
if operations[i] == "L":
p = nodes[p].left
elif operations[i] == "R":
p = nodes[p].right
else:
pair_id = nodes[p].pair
left = 0
right = 0
if p < pair_id:
left = p
right = pair_id
else:
left = pair_id
right = p
left_node = nodes[left].left
right_node = nodes[right].right
nodes[left_node].right = right_node
if right_node != n + 1:
nodes[right_node].left = left_node
p = right_node
else:
p = left_node
p = nodes[0].right
result = []
while p != n + 1:
result.append(brackets[p - 1])
p = nodes[p].right
print("".join(result))
```
| 84,648 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Recently Polycarp started to develop a text editor that works only with correct bracket sequences (abbreviated as CBS).
Note that a bracket sequence is correct if it is possible to get a correct mathematical expression by adding "+"-s and "1"-s to it. For example, sequences "(())()", "()" and "(()(()))" are correct, while ")(", "(()" and "(()))(" are not. Each bracket in CBS has a pair. For example, in "(()(()))":
* 1st bracket is paired with 8th,
* 2d bracket is paired with 3d,
* 3d bracket is paired with 2d,
* 4th bracket is paired with 7th,
* 5th bracket is paired with 6th,
* 6th bracket is paired with 5th,
* 7th bracket is paired with 4th,
* 8th bracket is paired with 1st.
Polycarp's editor currently supports only three operations during the use of CBS. The cursor in the editor takes the whole position of one of the brackets (not the position between the brackets!). There are three operations being supported:
* Β«LΒ» β move the cursor one position to the left,
* Β«RΒ» β move the cursor one position to the right,
* Β«DΒ» β delete the bracket in which the cursor is located, delete the bracket it's paired to and all brackets between them (that is, delete a substring between the bracket in which the cursor is located and the one it's paired to).
After the operation "D" the cursor moves to the nearest bracket to the right (of course, among the non-deleted). If there is no such bracket (that is, the suffix of the CBS was deleted), then the cursor moves to the nearest bracket to the left (of course, among the non-deleted).
There are pictures illustrated several usages of operation "D" below.
<image>
All incorrect operations (shift cursor over the end of CBS, delete the whole CBS, etc.) are not supported by Polycarp's editor.
Polycarp is very proud of his development, can you implement the functionality of his editor?
Input
The first line contains three positive integers n, m and p (2 β€ n β€ 500 000, 1 β€ m β€ 500 000, 1 β€ p β€ n) β the number of brackets in the correct bracket sequence, the number of operations and the initial position of cursor. Positions in the sequence are numbered from left to right, starting from one. It is guaranteed that n is even.
It is followed by the string of n characters "(" and ")" forming the correct bracket sequence.
Then follow a string of m characters "L", "R" and "D" β a sequence of the operations. Operations are carried out one by one from the first to the last. It is guaranteed that the given operations never move the cursor outside the bracket sequence, as well as the fact that after all operations a bracket sequence will be non-empty.
Output
Print the correct bracket sequence, obtained as a result of applying all operations to the initial sequence.
Examples
Input
8 4 5
(())()()
RDLD
Output
()
Input
12 5 3
((()())(()))
RRDLD
Output
(()(()))
Input
8 8 8
(())()()
LLLLLLDD
Output
()()
Note
In the first sample the cursor is initially at position 5. Consider actions of the editor:
1. command "R" β the cursor moves to the position 6 on the right;
2. command "D" β the deletion of brackets from the position 5 to the position 6. After that CBS takes the form (())(), the cursor is at the position 5;
3. command "L" β the cursor moves to the position 4 on the left;
4. command "D" β the deletion of brackets from the position 1 to the position 4. After that CBS takes the form (), the cursor is at the position 1.
Thus, the answer is equal to ().
Tags: data structures, dsu, strings
Correct Solution:
```
n, m, p = [int(x) for x in input().split()]
A = input().rstrip()
B = input().rstrip()
pair = [0] * n
stack = []
for (i, c) in enumerate(A):
if c == '(':
stack.append(i)
else:
j = stack.pop()
pair[i] = j
pair[j] = i
start = 0
pointer = p - 1
left = list(range(-1, n-1))
right = list(range(1, n+1))
left[0] = None
right[-1] = None
for c in B:
if c == 'R':
pointer = right[pointer]
elif c == 'L':
pointer = left[pointer]
else:
if pair[pointer] < pointer:
if right[pointer] is not None:
left[right[pointer]] = left[pair[pointer]]
if left[pair[pointer]] is not None:
right[left[pair[pointer]]] = right[pointer]
else:
start = right[pointer]
if right[pointer] is None:
pointer = left[pair[pointer]]
else:
pointer = right[pointer]
else:
if right[pair[pointer]] is not None:
left[right[pair[pointer]]] = left[pointer]
if left[pointer] is not None:
right[left[pointer]] = right[pair[pointer]]
else:
start = right[pair[pointer]]
if right[pair[pointer]] is None:
pointer = left[pointer]
else:
pointer = right[pair[pointer]]
i = start
while right[i] is not None:
print(A[i], end = '')
i = right[i]
print(A[i])
```
| 84,649 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Recently Polycarp started to develop a text editor that works only with correct bracket sequences (abbreviated as CBS).
Note that a bracket sequence is correct if it is possible to get a correct mathematical expression by adding "+"-s and "1"-s to it. For example, sequences "(())()", "()" and "(()(()))" are correct, while ")(", "(()" and "(()))(" are not. Each bracket in CBS has a pair. For example, in "(()(()))":
* 1st bracket is paired with 8th,
* 2d bracket is paired with 3d,
* 3d bracket is paired with 2d,
* 4th bracket is paired with 7th,
* 5th bracket is paired with 6th,
* 6th bracket is paired with 5th,
* 7th bracket is paired with 4th,
* 8th bracket is paired with 1st.
Polycarp's editor currently supports only three operations during the use of CBS. The cursor in the editor takes the whole position of one of the brackets (not the position between the brackets!). There are three operations being supported:
* Β«LΒ» β move the cursor one position to the left,
* Β«RΒ» β move the cursor one position to the right,
* Β«DΒ» β delete the bracket in which the cursor is located, delete the bracket it's paired to and all brackets between them (that is, delete a substring between the bracket in which the cursor is located and the one it's paired to).
After the operation "D" the cursor moves to the nearest bracket to the right (of course, among the non-deleted). If there is no such bracket (that is, the suffix of the CBS was deleted), then the cursor moves to the nearest bracket to the left (of course, among the non-deleted).
There are pictures illustrated several usages of operation "D" below.
<image>
All incorrect operations (shift cursor over the end of CBS, delete the whole CBS, etc.) are not supported by Polycarp's editor.
Polycarp is very proud of his development, can you implement the functionality of his editor?
Input
The first line contains three positive integers n, m and p (2 β€ n β€ 500 000, 1 β€ m β€ 500 000, 1 β€ p β€ n) β the number of brackets in the correct bracket sequence, the number of operations and the initial position of cursor. Positions in the sequence are numbered from left to right, starting from one. It is guaranteed that n is even.
It is followed by the string of n characters "(" and ")" forming the correct bracket sequence.
Then follow a string of m characters "L", "R" and "D" β a sequence of the operations. Operations are carried out one by one from the first to the last. It is guaranteed that the given operations never move the cursor outside the bracket sequence, as well as the fact that after all operations a bracket sequence will be non-empty.
Output
Print the correct bracket sequence, obtained as a result of applying all operations to the initial sequence.
Examples
Input
8 4 5
(())()()
RDLD
Output
()
Input
12 5 3
((()())(()))
RRDLD
Output
(()(()))
Input
8 8 8
(())()()
LLLLLLDD
Output
()()
Note
In the first sample the cursor is initially at position 5. Consider actions of the editor:
1. command "R" β the cursor moves to the position 6 on the right;
2. command "D" β the deletion of brackets from the position 5 to the position 6. After that CBS takes the form (())(), the cursor is at the position 5;
3. command "L" β the cursor moves to the position 4 on the left;
4. command "D" β the deletion of brackets from the position 1 to the position 4. After that CBS takes the form (), the cursor is at the position 1.
Thus, the answer is equal to ().
Tags: data structures, dsu, strings
Correct Solution:
```
def main():
n, m, p = map(int, input().split())
xlat, l, s, ll, lr = [0] * n, [], input(), list(range(-1, n)), list(range(1, n + 2))
p -= 1
for i, c in enumerate(s):
if c == '(':
l.append(i)
else:
j = l.pop()
xlat[i] = j
xlat[j] = i
for c in input():
if c == 'D':
if s[p] == '(':
p = xlat[p]
q = ll[xlat[p]]
p = lr[p]
ll[p], lr[q] = q, p
if p == n:
p = ll[p]
else:
p = (lr if c == 'R' else ll)[p]
q = p
while p != -1:
l.append(s[p])
p = ll[p]
l.reverse()
del l[-1]
while q != n:
l.append(s[q])
q = lr[q]
print(''.join(l))
if __name__ == '__main__':
main()
```
| 84,650 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Recently Polycarp started to develop a text editor that works only with correct bracket sequences (abbreviated as CBS).
Note that a bracket sequence is correct if it is possible to get a correct mathematical expression by adding "+"-s and "1"-s to it. For example, sequences "(())()", "()" and "(()(()))" are correct, while ")(", "(()" and "(()))(" are not. Each bracket in CBS has a pair. For example, in "(()(()))":
* 1st bracket is paired with 8th,
* 2d bracket is paired with 3d,
* 3d bracket is paired with 2d,
* 4th bracket is paired with 7th,
* 5th bracket is paired with 6th,
* 6th bracket is paired with 5th,
* 7th bracket is paired with 4th,
* 8th bracket is paired with 1st.
Polycarp's editor currently supports only three operations during the use of CBS. The cursor in the editor takes the whole position of one of the brackets (not the position between the brackets!). There are three operations being supported:
* Β«LΒ» β move the cursor one position to the left,
* Β«RΒ» β move the cursor one position to the right,
* Β«DΒ» β delete the bracket in which the cursor is located, delete the bracket it's paired to and all brackets between them (that is, delete a substring between the bracket in which the cursor is located and the one it's paired to).
After the operation "D" the cursor moves to the nearest bracket to the right (of course, among the non-deleted). If there is no such bracket (that is, the suffix of the CBS was deleted), then the cursor moves to the nearest bracket to the left (of course, among the non-deleted).
There are pictures illustrated several usages of operation "D" below.
<image>
All incorrect operations (shift cursor over the end of CBS, delete the whole CBS, etc.) are not supported by Polycarp's editor.
Polycarp is very proud of his development, can you implement the functionality of his editor?
Input
The first line contains three positive integers n, m and p (2 β€ n β€ 500 000, 1 β€ m β€ 500 000, 1 β€ p β€ n) β the number of brackets in the correct bracket sequence, the number of operations and the initial position of cursor. Positions in the sequence are numbered from left to right, starting from one. It is guaranteed that n is even.
It is followed by the string of n characters "(" and ")" forming the correct bracket sequence.
Then follow a string of m characters "L", "R" and "D" β a sequence of the operations. Operations are carried out one by one from the first to the last. It is guaranteed that the given operations never move the cursor outside the bracket sequence, as well as the fact that after all operations a bracket sequence will be non-empty.
Output
Print the correct bracket sequence, obtained as a result of applying all operations to the initial sequence.
Examples
Input
8 4 5
(())()()
RDLD
Output
()
Input
12 5 3
((()())(()))
RRDLD
Output
(()(()))
Input
8 8 8
(())()()
LLLLLLDD
Output
()()
Note
In the first sample the cursor is initially at position 5. Consider actions of the editor:
1. command "R" β the cursor moves to the position 6 on the right;
2. command "D" β the deletion of brackets from the position 5 to the position 6. After that CBS takes the form (())(), the cursor is at the position 5;
3. command "L" β the cursor moves to the position 4 on the left;
4. command "D" β the deletion of brackets from the position 1 to the position 4. After that CBS takes the form (), the cursor is at the position 1.
Thus, the answer is equal to ().
Tags: data structures, dsu, strings
Correct Solution:
```
class Node:
def __init__(self, index):
self.left = index - 1
self.right = index + 1
self.pair = -1
if __name__ == "__main__":
n, m, p = map(int, input().split())
brackets = input()
operations = input()
nodes = [Node(i) for i in range(n + 1)]
stack = []
for i in range(n):
if brackets[i] == "(":
stack.append(i + 1)
else:
pair_id = stack.pop()
nodes[pair_id].pair = i + 1
nodes[i + 1].pair = pair_id
for i in range(m):
if operations[i] == "L":
p = nodes[p].left
elif operations[i] == "R":
p = nodes[p].right
else:
pair_id = nodes[p].pair
left = min(p, pair_id)
right = max(p, pair_id)
left_node = nodes[left].left
right_node = nodes[right].right
nodes[left_node].right = right_node
if right_node != n + 1:
nodes[right_node].left = left_node
p = right_node
else:
p = left_node
p = nodes[0].right
result = []
while p != n + 1:
result.append(brackets[p - 1])
p = nodes[p].right
print("".join(result))
```
| 84,651 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Recently Polycarp started to develop a text editor that works only with correct bracket sequences (abbreviated as CBS).
Note that a bracket sequence is correct if it is possible to get a correct mathematical expression by adding "+"-s and "1"-s to it. For example, sequences "(())()", "()" and "(()(()))" are correct, while ")(", "(()" and "(()))(" are not. Each bracket in CBS has a pair. For example, in "(()(()))":
* 1st bracket is paired with 8th,
* 2d bracket is paired with 3d,
* 3d bracket is paired with 2d,
* 4th bracket is paired with 7th,
* 5th bracket is paired with 6th,
* 6th bracket is paired with 5th,
* 7th bracket is paired with 4th,
* 8th bracket is paired with 1st.
Polycarp's editor currently supports only three operations during the use of CBS. The cursor in the editor takes the whole position of one of the brackets (not the position between the brackets!). There are three operations being supported:
* Β«LΒ» β move the cursor one position to the left,
* Β«RΒ» β move the cursor one position to the right,
* Β«DΒ» β delete the bracket in which the cursor is located, delete the bracket it's paired to and all brackets between them (that is, delete a substring between the bracket in which the cursor is located and the one it's paired to).
After the operation "D" the cursor moves to the nearest bracket to the right (of course, among the non-deleted). If there is no such bracket (that is, the suffix of the CBS was deleted), then the cursor moves to the nearest bracket to the left (of course, among the non-deleted).
There are pictures illustrated several usages of operation "D" below.
<image>
All incorrect operations (shift cursor over the end of CBS, delete the whole CBS, etc.) are not supported by Polycarp's editor.
Polycarp is very proud of his development, can you implement the functionality of his editor?
Input
The first line contains three positive integers n, m and p (2 β€ n β€ 500 000, 1 β€ m β€ 500 000, 1 β€ p β€ n) β the number of brackets in the correct bracket sequence, the number of operations and the initial position of cursor. Positions in the sequence are numbered from left to right, starting from one. It is guaranteed that n is even.
It is followed by the string of n characters "(" and ")" forming the correct bracket sequence.
Then follow a string of m characters "L", "R" and "D" β a sequence of the operations. Operations are carried out one by one from the first to the last. It is guaranteed that the given operations never move the cursor outside the bracket sequence, as well as the fact that after all operations a bracket sequence will be non-empty.
Output
Print the correct bracket sequence, obtained as a result of applying all operations to the initial sequence.
Examples
Input
8 4 5
(())()()
RDLD
Output
()
Input
12 5 3
((()())(()))
RRDLD
Output
(()(()))
Input
8 8 8
(())()()
LLLLLLDD
Output
()()
Note
In the first sample the cursor is initially at position 5. Consider actions of the editor:
1. command "R" β the cursor moves to the position 6 on the right;
2. command "D" β the deletion of brackets from the position 5 to the position 6. After that CBS takes the form (())(), the cursor is at the position 5;
3. command "L" β the cursor moves to the position 4 on the left;
4. command "D" β the deletion of brackets from the position 1 to the position 4. After that CBS takes the form (), the cursor is at the position 1.
Thus, the answer is equal to ().
Tags: data structures, dsu, strings
Correct Solution:
```
jump_r = {}
jump_l = {}
def bracket_to_value(bracket):
if bracket == '(':
return 1
if bracket == ')':
return -1
def move_r(c):
if c+1 in jump_r:
return jump_r[c+1]+1
else:
return c+1
def move_l(c):
if c-1 in jump_l:
return jump_l[c-1]-1
else:
return c-1
def remove_bracket(s, c, length):
val = bracket_to_value(s[c])
initial_c = c
dir = bracket_to_value(s[c])
#print(f'started at c ={c} and dir = {dir}')
if dir == 1:
c = move_r(c)
if dir == -1:
c = move_l(c)
val += bracket_to_value(s[c])
while val != 0:
#print(f'wwwc = {c} val = {val} s[c] = {s[c]}')
if dir == 1:
c = move_r(c)
if dir == -1:
c = move_l(c)
val += bracket_to_value(s[c])
final_c = c
left_end = min(initial_c, final_c)
right_end = max(initial_c, final_c)
real_r_end = right_end
real_l_end = left_end
#print(f'left_end = {left_end} roght_end = {right_end}')
jump_r[left_end] = right_end
jump_l[right_end] = left_end
if right_end + 1 in jump_r:
real_r_end = jump_r[right_end+1]
if left_end - 1 in jump_l:
real_l_end = jump_l[left_end-1]
jump_l[real_r_end] = real_l_end
jump_r[real_l_end] = real_r_end
if real_r_end < length - 1:
new_c = real_r_end+1
else:
new_c = real_l_end - 1
return new_c
def smart_print(s):
i = 0
while i < n:
if i not in jump_r:
print(s[i], end='')
i += 1
else:
i = jump_r[i]+1
def perform_order(order, s, c, length):
if order == 'R':
return move_r(c)
if order == 'L':
return move_l(c)
if order == 'D':
return remove_bracket(s, c, length)
n, m, p = [int(x) for x in input().split()]
p = p-1
se = input()
orders = input()
for ord in orders:
p = perform_order(ord, se, p, n)
#print(f'jump_r = {jump_r} jump_l = {jump_l} p = {p} s = {se}')
smart_print(se)
# print(f'se = {se} p = {p}')
#print(jump_r)
# 3->6
#
# 0 1 2 3 4 5 6 7 8 9 10 11
# ( ( ( ) ( ) ) ( ( ) ) )
```
| 84,652 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Recently Polycarp started to develop a text editor that works only with correct bracket sequences (abbreviated as CBS).
Note that a bracket sequence is correct if it is possible to get a correct mathematical expression by adding "+"-s and "1"-s to it. For example, sequences "(())()", "()" and "(()(()))" are correct, while ")(", "(()" and "(()))(" are not. Each bracket in CBS has a pair. For example, in "(()(()))":
* 1st bracket is paired with 8th,
* 2d bracket is paired with 3d,
* 3d bracket is paired with 2d,
* 4th bracket is paired with 7th,
* 5th bracket is paired with 6th,
* 6th bracket is paired with 5th,
* 7th bracket is paired with 4th,
* 8th bracket is paired with 1st.
Polycarp's editor currently supports only three operations during the use of CBS. The cursor in the editor takes the whole position of one of the brackets (not the position between the brackets!). There are three operations being supported:
* Β«LΒ» β move the cursor one position to the left,
* Β«RΒ» β move the cursor one position to the right,
* Β«DΒ» β delete the bracket in which the cursor is located, delete the bracket it's paired to and all brackets between them (that is, delete a substring between the bracket in which the cursor is located and the one it's paired to).
After the operation "D" the cursor moves to the nearest bracket to the right (of course, among the non-deleted). If there is no such bracket (that is, the suffix of the CBS was deleted), then the cursor moves to the nearest bracket to the left (of course, among the non-deleted).
There are pictures illustrated several usages of operation "D" below.
<image>
All incorrect operations (shift cursor over the end of CBS, delete the whole CBS, etc.) are not supported by Polycarp's editor.
Polycarp is very proud of his development, can you implement the functionality of his editor?
Input
The first line contains three positive integers n, m and p (2 β€ n β€ 500 000, 1 β€ m β€ 500 000, 1 β€ p β€ n) β the number of brackets in the correct bracket sequence, the number of operations and the initial position of cursor. Positions in the sequence are numbered from left to right, starting from one. It is guaranteed that n is even.
It is followed by the string of n characters "(" and ")" forming the correct bracket sequence.
Then follow a string of m characters "L", "R" and "D" β a sequence of the operations. Operations are carried out one by one from the first to the last. It is guaranteed that the given operations never move the cursor outside the bracket sequence, as well as the fact that after all operations a bracket sequence will be non-empty.
Output
Print the correct bracket sequence, obtained as a result of applying all operations to the initial sequence.
Examples
Input
8 4 5
(())()()
RDLD
Output
()
Input
12 5 3
((()())(()))
RRDLD
Output
(()(()))
Input
8 8 8
(())()()
LLLLLLDD
Output
()()
Note
In the first sample the cursor is initially at position 5. Consider actions of the editor:
1. command "R" β the cursor moves to the position 6 on the right;
2. command "D" β the deletion of brackets from the position 5 to the position 6. After that CBS takes the form (())(), the cursor is at the position 5;
3. command "L" β the cursor moves to the position 4 on the left;
4. command "D" β the deletion of brackets from the position 1 to the position 4. After that CBS takes the form (), the cursor is at the position 1.
Thus, the answer is equal to ().
Tags: data structures, dsu, strings
Correct Solution:
```
n, m, p = map(int, input().split()); x, v, s, l, r = [0]*n, [], input(), list(range(-1, n)), list(range(1, n+2))
p -= 1
for i, c in enumerate(s):
if c == '(': v.append(i)
else:
j = v.pop()
x[i] = j
x[j] = i
for c in input():
if c == 'D':
if s[p] == '(':
p = x[p]
q = l[x[p]]
p = r[p]
l[p], r[q] = q, p
if p == n:
p = l[p]
else:
p = (r if c == 'R' else l)[p]
q = p
while p != -1:
v.append(s[p])
p = l[p]
v.reverse()
del v[-1]
while q != n:
v.append(s[q])
q = r[q]
print(''.join(v))
```
| 84,653 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Recently Polycarp started to develop a text editor that works only with correct bracket sequences (abbreviated as CBS).
Note that a bracket sequence is correct if it is possible to get a correct mathematical expression by adding "+"-s and "1"-s to it. For example, sequences "(())()", "()" and "(()(()))" are correct, while ")(", "(()" and "(()))(" are not. Each bracket in CBS has a pair. For example, in "(()(()))":
* 1st bracket is paired with 8th,
* 2d bracket is paired with 3d,
* 3d bracket is paired with 2d,
* 4th bracket is paired with 7th,
* 5th bracket is paired with 6th,
* 6th bracket is paired with 5th,
* 7th bracket is paired with 4th,
* 8th bracket is paired with 1st.
Polycarp's editor currently supports only three operations during the use of CBS. The cursor in the editor takes the whole position of one of the brackets (not the position between the brackets!). There are three operations being supported:
* Β«LΒ» β move the cursor one position to the left,
* Β«RΒ» β move the cursor one position to the right,
* Β«DΒ» β delete the bracket in which the cursor is located, delete the bracket it's paired to and all brackets between them (that is, delete a substring between the bracket in which the cursor is located and the one it's paired to).
After the operation "D" the cursor moves to the nearest bracket to the right (of course, among the non-deleted). If there is no such bracket (that is, the suffix of the CBS was deleted), then the cursor moves to the nearest bracket to the left (of course, among the non-deleted).
There are pictures illustrated several usages of operation "D" below.
<image>
All incorrect operations (shift cursor over the end of CBS, delete the whole CBS, etc.) are not supported by Polycarp's editor.
Polycarp is very proud of his development, can you implement the functionality of his editor?
Input
The first line contains three positive integers n, m and p (2 β€ n β€ 500 000, 1 β€ m β€ 500 000, 1 β€ p β€ n) β the number of brackets in the correct bracket sequence, the number of operations and the initial position of cursor. Positions in the sequence are numbered from left to right, starting from one. It is guaranteed that n is even.
It is followed by the string of n characters "(" and ")" forming the correct bracket sequence.
Then follow a string of m characters "L", "R" and "D" β a sequence of the operations. Operations are carried out one by one from the first to the last. It is guaranteed that the given operations never move the cursor outside the bracket sequence, as well as the fact that after all operations a bracket sequence will be non-empty.
Output
Print the correct bracket sequence, obtained as a result of applying all operations to the initial sequence.
Examples
Input
8 4 5
(())()()
RDLD
Output
()
Input
12 5 3
((()())(()))
RRDLD
Output
(()(()))
Input
8 8 8
(())()()
LLLLLLDD
Output
()()
Note
In the first sample the cursor is initially at position 5. Consider actions of the editor:
1. command "R" β the cursor moves to the position 6 on the right;
2. command "D" β the deletion of brackets from the position 5 to the position 6. After that CBS takes the form (())(), the cursor is at the position 5;
3. command "L" β the cursor moves to the position 4 on the left;
4. command "D" β the deletion of brackets from the position 1 to the position 4. After that CBS takes the form (), the cursor is at the position 1.
Thus, the answer is equal to ().
Submitted Solution:
```
n, m, p = input().split(' ')
n = int(n)
m = int(m)
p = int(p) - 1
bracket = list(input())
operation = list(input())
blist = list(bracket)
c = 1
co = 0
cm = 1
cc = 0
for i in range(n):
if bracket[i] == "(":
blist[i] = c
cm = c
c += 1
continue
elif bracket[i] == ")":
blist[i] = -cm
cc += 1
if cc == c: co = c
cm = co + c - cc - 1
continue
print(blist)
exit()
for i in range(m):
if operation[i] == "R":
p += 1
continue
elif operation[i] == "L":
p -= 1
continue
elif operation[i] == "D":
if blist[p] > 0:
temp = blist.index(-blist[p])
del(blist[p:temp+1])
#p = temp
else:
temp = blist.index(-blist[p])
del(blist[p:temp:-1])
del(blist[temp])
p = temp
if p > len(blist) -1 :
p = len(blist) -1
res = ""
for i in range(len(blist)):
if blist[i] > 0:
res = res + "("
else:
res = res + ")"
print(res)
```
No
| 84,654 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Recently Polycarp started to develop a text editor that works only with correct bracket sequences (abbreviated as CBS).
Note that a bracket sequence is correct if it is possible to get a correct mathematical expression by adding "+"-s and "1"-s to it. For example, sequences "(())()", "()" and "(()(()))" are correct, while ")(", "(()" and "(()))(" are not. Each bracket in CBS has a pair. For example, in "(()(()))":
* 1st bracket is paired with 8th,
* 2d bracket is paired with 3d,
* 3d bracket is paired with 2d,
* 4th bracket is paired with 7th,
* 5th bracket is paired with 6th,
* 6th bracket is paired with 5th,
* 7th bracket is paired with 4th,
* 8th bracket is paired with 1st.
Polycarp's editor currently supports only three operations during the use of CBS. The cursor in the editor takes the whole position of one of the brackets (not the position between the brackets!). There are three operations being supported:
* Β«LΒ» β move the cursor one position to the left,
* Β«RΒ» β move the cursor one position to the right,
* Β«DΒ» β delete the bracket in which the cursor is located, delete the bracket it's paired to and all brackets between them (that is, delete a substring between the bracket in which the cursor is located and the one it's paired to).
After the operation "D" the cursor moves to the nearest bracket to the right (of course, among the non-deleted). If there is no such bracket (that is, the suffix of the CBS was deleted), then the cursor moves to the nearest bracket to the left (of course, among the non-deleted).
There are pictures illustrated several usages of operation "D" below.
<image>
All incorrect operations (shift cursor over the end of CBS, delete the whole CBS, etc.) are not supported by Polycarp's editor.
Polycarp is very proud of his development, can you implement the functionality of his editor?
Input
The first line contains three positive integers n, m and p (2 β€ n β€ 500 000, 1 β€ m β€ 500 000, 1 β€ p β€ n) β the number of brackets in the correct bracket sequence, the number of operations and the initial position of cursor. Positions in the sequence are numbered from left to right, starting from one. It is guaranteed that n is even.
It is followed by the string of n characters "(" and ")" forming the correct bracket sequence.
Then follow a string of m characters "L", "R" and "D" β a sequence of the operations. Operations are carried out one by one from the first to the last. It is guaranteed that the given operations never move the cursor outside the bracket sequence, as well as the fact that after all operations a bracket sequence will be non-empty.
Output
Print the correct bracket sequence, obtained as a result of applying all operations to the initial sequence.
Examples
Input
8 4 5
(())()()
RDLD
Output
()
Input
12 5 3
((()())(()))
RRDLD
Output
(()(()))
Input
8 8 8
(())()()
LLLLLLDD
Output
()()
Note
In the first sample the cursor is initially at position 5. Consider actions of the editor:
1. command "R" β the cursor moves to the position 6 on the right;
2. command "D" β the deletion of brackets from the position 5 to the position 6. After that CBS takes the form (())(), the cursor is at the position 5;
3. command "L" β the cursor moves to the position 4 on the left;
4. command "D" β the deletion of brackets from the position 1 to the position 4. After that CBS takes the form (), the cursor is at the position 1.
Thus, the answer is equal to ().
Submitted Solution:
```
def preproc(str, leng):
li = []
res = [-1]*leng
for i in range(leng):
if str[i] == '(':
li.append(i)
else:
start, end = li.pop(), i
res[start] = end
res[end] = start
return res
def delete(flags, cursor, pairs):
pos = pairs[cursor]
direction = 1 if pos > cursor else -1
while(pos+direction > 0 and pos+direction < len(flags) and flags[pos+direction] != -1):
pos = flags[pos+direction]
return pos
leng, op_num, cursor = map(int, input().strip().split())
cursor = cursor-1
str = input().strip()
ops = input().strip()
pairs = preproc(str, leng)
flags = [-1]*leng
#print(leng, op_num, cursor, str, ops, pairs)
for i in ops:
#print(i, cursor, flags)
if i == 'R' or i == 'L':
cursor = {
'R':(lambda cursor=cursor, flags=flags: cursor+1 if flags[cursor+1] == -1 else flags[cursor+1]+1),
'L':(lambda cursor=cursor, flags=flags: cursor-1 if flags[cursor-1] == -1 else flags[cursor-1]-1)
}[i]()
else:
delete_to = delete(flags, cursor, pairs)
flags[cursor] = delete_to
flags[delete_to] = cursor
if max(cursor, delete_to)+1 < leng:
cursor = max(cursor, delete_to)+1
else:
cursor = cursor-1 if flags[cursor-1] == -1 else flags[cursor-1]
idx = 0
res = ''
while idx < leng:
if flags[idx] != -1:
idx = flags[idx]+1
continue
res += str[idx]
idx = idx+1
print(res)
```
No
| 84,655 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Recently Polycarp started to develop a text editor that works only with correct bracket sequences (abbreviated as CBS).
Note that a bracket sequence is correct if it is possible to get a correct mathematical expression by adding "+"-s and "1"-s to it. For example, sequences "(())()", "()" and "(()(()))" are correct, while ")(", "(()" and "(()))(" are not. Each bracket in CBS has a pair. For example, in "(()(()))":
* 1st bracket is paired with 8th,
* 2d bracket is paired with 3d,
* 3d bracket is paired with 2d,
* 4th bracket is paired with 7th,
* 5th bracket is paired with 6th,
* 6th bracket is paired with 5th,
* 7th bracket is paired with 4th,
* 8th bracket is paired with 1st.
Polycarp's editor currently supports only three operations during the use of CBS. The cursor in the editor takes the whole position of one of the brackets (not the position between the brackets!). There are three operations being supported:
* Β«LΒ» β move the cursor one position to the left,
* Β«RΒ» β move the cursor one position to the right,
* Β«DΒ» β delete the bracket in which the cursor is located, delete the bracket it's paired to and all brackets between them (that is, delete a substring between the bracket in which the cursor is located and the one it's paired to).
After the operation "D" the cursor moves to the nearest bracket to the right (of course, among the non-deleted). If there is no such bracket (that is, the suffix of the CBS was deleted), then the cursor moves to the nearest bracket to the left (of course, among the non-deleted).
There are pictures illustrated several usages of operation "D" below.
<image>
All incorrect operations (shift cursor over the end of CBS, delete the whole CBS, etc.) are not supported by Polycarp's editor.
Polycarp is very proud of his development, can you implement the functionality of his editor?
Input
The first line contains three positive integers n, m and p (2 β€ n β€ 500 000, 1 β€ m β€ 500 000, 1 β€ p β€ n) β the number of brackets in the correct bracket sequence, the number of operations and the initial position of cursor. Positions in the sequence are numbered from left to right, starting from one. It is guaranteed that n is even.
It is followed by the string of n characters "(" and ")" forming the correct bracket sequence.
Then follow a string of m characters "L", "R" and "D" β a sequence of the operations. Operations are carried out one by one from the first to the last. It is guaranteed that the given operations never move the cursor outside the bracket sequence, as well as the fact that after all operations a bracket sequence will be non-empty.
Output
Print the correct bracket sequence, obtained as a result of applying all operations to the initial sequence.
Examples
Input
8 4 5
(())()()
RDLD
Output
()
Input
12 5 3
((()())(()))
RRDLD
Output
(()(()))
Input
8 8 8
(())()()
LLLLLLDD
Output
()()
Note
In the first sample the cursor is initially at position 5. Consider actions of the editor:
1. command "R" β the cursor moves to the position 6 on the right;
2. command "D" β the deletion of brackets from the position 5 to the position 6. After that CBS takes the form (())(), the cursor is at the position 5;
3. command "L" β the cursor moves to the position 4 on the left;
4. command "D" β the deletion of brackets from the position 1 to the position 4. After that CBS takes the form (), the cursor is at the position 1.
Thus, the answer is equal to ().
Submitted Solution:
```
n, m, p = input().split(' ')
n = int(n)
m = int(m)
p = int(p) - 1
bracket = list(input())
operation = list(input())
blist = list(bracket)
c = 1
co = 0
cm = 1
for i in range(n):
if bracket[i] == "(":
blist[i] = c
cm = c
co += 1
c += 1
continue
elif bracket[i] == ")":
blist[i] = -cm
co -= 1
cm = c - co
continue
for i in range(m):
if operation[i] == "R":
p += 1
continue
elif operation[i] == "L":
p -= 1
continue
elif operation[i] == "D":
if blist[p] > 0:
temp = blist.index(-blist[p])
del(blist[p:temp+1])
#p = temp
else:
temp = blist.index(-blist[p])
del(blist[p:temp:-1])
del(blist[temp])
p = temp
if p > len(blist) -1 :
p = len(blist) -1
res = ""
for i in range(len(blist)):
if blist[i] > 0:
res = res + "("
else:
res = res + ")"
print(res)
```
No
| 84,656 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Recently Polycarp started to develop a text editor that works only with correct bracket sequences (abbreviated as CBS).
Note that a bracket sequence is correct if it is possible to get a correct mathematical expression by adding "+"-s and "1"-s to it. For example, sequences "(())()", "()" and "(()(()))" are correct, while ")(", "(()" and "(()))(" are not. Each bracket in CBS has a pair. For example, in "(()(()))":
* 1st bracket is paired with 8th,
* 2d bracket is paired with 3d,
* 3d bracket is paired with 2d,
* 4th bracket is paired with 7th,
* 5th bracket is paired with 6th,
* 6th bracket is paired with 5th,
* 7th bracket is paired with 4th,
* 8th bracket is paired with 1st.
Polycarp's editor currently supports only three operations during the use of CBS. The cursor in the editor takes the whole position of one of the brackets (not the position between the brackets!). There are three operations being supported:
* Β«LΒ» β move the cursor one position to the left,
* Β«RΒ» β move the cursor one position to the right,
* Β«DΒ» β delete the bracket in which the cursor is located, delete the bracket it's paired to and all brackets between them (that is, delete a substring between the bracket in which the cursor is located and the one it's paired to).
After the operation "D" the cursor moves to the nearest bracket to the right (of course, among the non-deleted). If there is no such bracket (that is, the suffix of the CBS was deleted), then the cursor moves to the nearest bracket to the left (of course, among the non-deleted).
There are pictures illustrated several usages of operation "D" below.
<image>
All incorrect operations (shift cursor over the end of CBS, delete the whole CBS, etc.) are not supported by Polycarp's editor.
Polycarp is very proud of his development, can you implement the functionality of his editor?
Input
The first line contains three positive integers n, m and p (2 β€ n β€ 500 000, 1 β€ m β€ 500 000, 1 β€ p β€ n) β the number of brackets in the correct bracket sequence, the number of operations and the initial position of cursor. Positions in the sequence are numbered from left to right, starting from one. It is guaranteed that n is even.
It is followed by the string of n characters "(" and ")" forming the correct bracket sequence.
Then follow a string of m characters "L", "R" and "D" β a sequence of the operations. Operations are carried out one by one from the first to the last. It is guaranteed that the given operations never move the cursor outside the bracket sequence, as well as the fact that after all operations a bracket sequence will be non-empty.
Output
Print the correct bracket sequence, obtained as a result of applying all operations to the initial sequence.
Examples
Input
8 4 5
(())()()
RDLD
Output
()
Input
12 5 3
((()())(()))
RRDLD
Output
(()(()))
Input
8 8 8
(())()()
LLLLLLDD
Output
()()
Note
In the first sample the cursor is initially at position 5. Consider actions of the editor:
1. command "R" β the cursor moves to the position 6 on the right;
2. command "D" β the deletion of brackets from the position 5 to the position 6. After that CBS takes the form (())(), the cursor is at the position 5;
3. command "L" β the cursor moves to the position 4 on the left;
4. command "D" β the deletion of brackets from the position 1 to the position 4. After that CBS takes the form (), the cursor is at the position 1.
Thus, the answer is equal to ().
Submitted Solution:
```
n, m, p = input().split(' ')
n = int(n)
m = int(m)
p = int(p) - 1
bracket = list(input())
operation = list(input())
blist = list(bracket)
c = 1
co = 0
cm = 0
for i in range(n):
if bracket[i] == "(":
blist[i] = c
co += 1
if co == 1:
cm = c
else:
cm = c
c += 1
continue
elif bracket[i] == ")":
blist[i] = -cm
co -= 1
cm = co
continue
for i in range(m):
if operation[i] == "R":
p += 1
continue
elif operation[i] == "L":
p -= 1
continue
elif operation[i] == "D":
if blist[p] > 0:
temp = blist.index(-blist[p])
del(blist[p:temp+1])
#p = temp
else:
temp = blist.index(-blist[p])
del(blist[p:temp:-1])
del(blist[temp])
p = temp
if p > len(blist) -1 :
p = len(blist) -1
res = ""
for i in range(len(blist)):
if blist[i] > 0:
res = res + "("
else:
res = res + ")"
print(res)
```
No
| 84,657 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Barney lives in country USC (United States of Charzeh). USC has n cities numbered from 1 through n and n - 1 roads between them. Cities and roads of USC form a rooted tree (Barney's not sure why it is rooted). Root of the tree is the city number 1. Thus if one will start his journey from city 1, he can visit any city he wants by following roads.
<image>
Some girl has stolen Barney's heart, and Barney wants to find her. He starts looking for in the root of the tree and (since he is Barney Stinson not a random guy), he uses a random DFS to search in the cities. A pseudo code of this algorithm is as follows:
let starting_time be an array of length n
current_time = 0
dfs(v):
current_time = current_time + 1
starting_time[v] = current_time
shuffle children[v] randomly (each permutation with equal possibility)
// children[v] is vector of children cities of city v
for u in children[v]:
dfs(u)
As told before, Barney will start his journey in the root of the tree (equivalent to call dfs(1)).
Now Barney needs to pack a backpack and so he wants to know more about his upcoming journey: for every city i, Barney wants to know the expected value of starting_time[i]. He's a friend of Jon Snow and knows nothing, that's why he asked for your help.
Input
The first line of input contains a single integer n (1 β€ n β€ 105) β the number of cities in USC.
The second line contains n - 1 integers p2, p3, ..., pn (1 β€ pi < i), where pi is the number of the parent city of city number i in the tree, meaning there is a road between cities numbered pi and i in USC.
Output
In the first and only line of output print n numbers, where i-th number is the expected value of starting_time[i].
Your answer for each city will be considered correct if its absolute or relative error does not exceed 10 - 6.
Examples
Input
7
1 2 1 1 4 4
Output
1.0 4.0 5.0 3.5 4.5 5.0 5.0
Input
12
1 1 2 2 4 4 3 3 1 10 8
Output
1.0 5.0 5.5 6.5 7.5 8.0 8.0 7.0 7.5 6.5 7.5 8.0
Tags: dfs and similar, math, probabilities, trees
Correct Solution:
```
n = int(input())
pos, tree, ans, sz = list(map(int,input().split())) if n > 1 else [],[],[],[]
for i in range(n):
tree.append([])
ans.append(0.0)
sz.append(0)
for i in range(n - 1):
tree[pos[i] - 1].append(i + 1)
for i in range(n)[::-1]:
sz[i] = 1
for to in tree[i]:
sz[i] += sz[to]
for i in range(n):
for to in tree[i]:
ans[to] = ans[i] + 1 + (sz[i] - 1 - sz[to]) * 0.5
st = lambda i: str(i + 1)
print(' '.join(list(map(st, ans))))
# Made By Mostafa_Khaled
```
| 84,658 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Barney lives in country USC (United States of Charzeh). USC has n cities numbered from 1 through n and n - 1 roads between them. Cities and roads of USC form a rooted tree (Barney's not sure why it is rooted). Root of the tree is the city number 1. Thus if one will start his journey from city 1, he can visit any city he wants by following roads.
<image>
Some girl has stolen Barney's heart, and Barney wants to find her. He starts looking for in the root of the tree and (since he is Barney Stinson not a random guy), he uses a random DFS to search in the cities. A pseudo code of this algorithm is as follows:
let starting_time be an array of length n
current_time = 0
dfs(v):
current_time = current_time + 1
starting_time[v] = current_time
shuffle children[v] randomly (each permutation with equal possibility)
// children[v] is vector of children cities of city v
for u in children[v]:
dfs(u)
As told before, Barney will start his journey in the root of the tree (equivalent to call dfs(1)).
Now Barney needs to pack a backpack and so he wants to know more about his upcoming journey: for every city i, Barney wants to know the expected value of starting_time[i]. He's a friend of Jon Snow and knows nothing, that's why he asked for your help.
Input
The first line of input contains a single integer n (1 β€ n β€ 105) β the number of cities in USC.
The second line contains n - 1 integers p2, p3, ..., pn (1 β€ pi < i), where pi is the number of the parent city of city number i in the tree, meaning there is a road between cities numbered pi and i in USC.
Output
In the first and only line of output print n numbers, where i-th number is the expected value of starting_time[i].
Your answer for each city will be considered correct if its absolute or relative error does not exceed 10 - 6.
Examples
Input
7
1 2 1 1 4 4
Output
1.0 4.0 5.0 3.5 4.5 5.0 5.0
Input
12
1 1 2 2 4 4 3 3 1 10 8
Output
1.0 5.0 5.5 6.5 7.5 8.0 8.0 7.0 7.5 6.5 7.5 8.0
Tags: dfs and similar, math, probabilities, trees
Correct Solution:
```
# [https://gitlab.com/amirmd76/cf-round-362/-/blob/master/B/dans.py <- https://gitlab.com/amirmd76/cf-round-362/tree/master/B <- https://codeforces.com/blog/entry/46031 <- https://codeforces.com/problemset/problem/696/B <- https://algoprog.ru/material/pc696pB]
n = int(input())
if n > 1:
p = input().split(' ')
else:
p = []
g = []
ans = []
sz = []
for i in range(0, n):
g.append([])
ans.append(0.0)
sz.append(0)
for i in range(0, n - 1):
g[int(p[i]) - 1].append(i + 1)
for i in range(0, n)[::-1]:
sz[i] = 1
for to in g[i]:
sz[i] += sz[to]
for i in range(0, n):
for to in g[i]:
ans[to] = ans[i] + 1 + (sz[i] - 1 - sz[to]) * 0.5
print(' '.join([str(a + 1) for a in ans]))
```
| 84,659 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Barney lives in country USC (United States of Charzeh). USC has n cities numbered from 1 through n and n - 1 roads between them. Cities and roads of USC form a rooted tree (Barney's not sure why it is rooted). Root of the tree is the city number 1. Thus if one will start his journey from city 1, he can visit any city he wants by following roads.
<image>
Some girl has stolen Barney's heart, and Barney wants to find her. He starts looking for in the root of the tree and (since he is Barney Stinson not a random guy), he uses a random DFS to search in the cities. A pseudo code of this algorithm is as follows:
let starting_time be an array of length n
current_time = 0
dfs(v):
current_time = current_time + 1
starting_time[v] = current_time
shuffle children[v] randomly (each permutation with equal possibility)
// children[v] is vector of children cities of city v
for u in children[v]:
dfs(u)
As told before, Barney will start his journey in the root of the tree (equivalent to call dfs(1)).
Now Barney needs to pack a backpack and so he wants to know more about his upcoming journey: for every city i, Barney wants to know the expected value of starting_time[i]. He's a friend of Jon Snow and knows nothing, that's why he asked for your help.
Input
The first line of input contains a single integer n (1 β€ n β€ 105) β the number of cities in USC.
The second line contains n - 1 integers p2, p3, ..., pn (1 β€ pi < i), where pi is the number of the parent city of city number i in the tree, meaning there is a road between cities numbered pi and i in USC.
Output
In the first and only line of output print n numbers, where i-th number is the expected value of starting_time[i].
Your answer for each city will be considered correct if its absolute or relative error does not exceed 10 - 6.
Examples
Input
7
1 2 1 1 4 4
Output
1.0 4.0 5.0 3.5 4.5 5.0 5.0
Input
12
1 1 2 2 4 4 3 3 1 10 8
Output
1.0 5.0 5.5 6.5 7.5 8.0 8.0 7.0 7.5 6.5 7.5 8.0
Tags: dfs and similar, math, probabilities, trees
Correct Solution:
```
n = int(input())
if n ==1:
print(1)
exit(0)
l = list(map(int,input().split()))
w = [[]for i in range(n)]
sz = [1]*n
for i in range(n-1):
w[l[i]-1].append(i+1)
for i in range(n-1,-1,-1):
for j in range(len(w[i])):
sz[i]+=sz[w[i][j]]
ans = [0]*n
for i in range(n):
for j in range(len(w[i])):
ans[w[i][j]] = ans[i]+1+(sz[i]-1-sz[w[i][j]])/2
for i in range(n):
print(ans[i]+1,end = " ")
```
| 84,660 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Barney lives in country USC (United States of Charzeh). USC has n cities numbered from 1 through n and n - 1 roads between them. Cities and roads of USC form a rooted tree (Barney's not sure why it is rooted). Root of the tree is the city number 1. Thus if one will start his journey from city 1, he can visit any city he wants by following roads.
<image>
Some girl has stolen Barney's heart, and Barney wants to find her. He starts looking for in the root of the tree and (since he is Barney Stinson not a random guy), he uses a random DFS to search in the cities. A pseudo code of this algorithm is as follows:
let starting_time be an array of length n
current_time = 0
dfs(v):
current_time = current_time + 1
starting_time[v] = current_time
shuffle children[v] randomly (each permutation with equal possibility)
// children[v] is vector of children cities of city v
for u in children[v]:
dfs(u)
As told before, Barney will start his journey in the root of the tree (equivalent to call dfs(1)).
Now Barney needs to pack a backpack and so he wants to know more about his upcoming journey: for every city i, Barney wants to know the expected value of starting_time[i]. He's a friend of Jon Snow and knows nothing, that's why he asked for your help.
Input
The first line of input contains a single integer n (1 β€ n β€ 105) β the number of cities in USC.
The second line contains n - 1 integers p2, p3, ..., pn (1 β€ pi < i), where pi is the number of the parent city of city number i in the tree, meaning there is a road between cities numbered pi and i in USC.
Output
In the first and only line of output print n numbers, where i-th number is the expected value of starting_time[i].
Your answer for each city will be considered correct if its absolute or relative error does not exceed 10 - 6.
Examples
Input
7
1 2 1 1 4 4
Output
1.0 4.0 5.0 3.5 4.5 5.0 5.0
Input
12
1 1 2 2 4 4 3 3 1 10 8
Output
1.0 5.0 5.5 6.5 7.5 8.0 8.0 7.0 7.5 6.5 7.5 8.0
Tags: dfs and similar, math, probabilities, trees
Correct Solution:
```
n = int(input())
pos,tree,ans,sz = list(map(int,input().split())) if n > 1 else [],[],[],[]
for i in range(n):
tree.append([])
ans.append(0.0)
sz.append(0)
for i in range(n-1):
tree[pos[i]-1].append(i+1)
for i in range(n)[::-1]:
sz[i] = 1
for to in tree[i]:
sz[i] += sz[to]
for i in range(n):
for to in tree[i]:
ans[to] = ans[i] + 1 + (sz[i]-1-sz[to]) * 0.5
st = lambda i: str(i+1)
print(' '.join(list(map(st,ans))))
```
| 84,661 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Barney lives in country USC (United States of Charzeh). USC has n cities numbered from 1 through n and n - 1 roads between them. Cities and roads of USC form a rooted tree (Barney's not sure why it is rooted). Root of the tree is the city number 1. Thus if one will start his journey from city 1, he can visit any city he wants by following roads.
<image>
Some girl has stolen Barney's heart, and Barney wants to find her. He starts looking for in the root of the tree and (since he is Barney Stinson not a random guy), he uses a random DFS to search in the cities. A pseudo code of this algorithm is as follows:
let starting_time be an array of length n
current_time = 0
dfs(v):
current_time = current_time + 1
starting_time[v] = current_time
shuffle children[v] randomly (each permutation with equal possibility)
// children[v] is vector of children cities of city v
for u in children[v]:
dfs(u)
As told before, Barney will start his journey in the root of the tree (equivalent to call dfs(1)).
Now Barney needs to pack a backpack and so he wants to know more about his upcoming journey: for every city i, Barney wants to know the expected value of starting_time[i]. He's a friend of Jon Snow and knows nothing, that's why he asked for your help.
Input
The first line of input contains a single integer n (1 β€ n β€ 105) β the number of cities in USC.
The second line contains n - 1 integers p2, p3, ..., pn (1 β€ pi < i), where pi is the number of the parent city of city number i in the tree, meaning there is a road between cities numbered pi and i in USC.
Output
In the first and only line of output print n numbers, where i-th number is the expected value of starting_time[i].
Your answer for each city will be considered correct if its absolute or relative error does not exceed 10 - 6.
Examples
Input
7
1 2 1 1 4 4
Output
1.0 4.0 5.0 3.5 4.5 5.0 5.0
Input
12
1 1 2 2 4 4 3 3 1 10 8
Output
1.0 5.0 5.5 6.5 7.5 8.0 8.0 7.0 7.5 6.5 7.5 8.0
Tags: dfs and similar, math, probabilities, trees
Correct Solution:
```
import sys
input = sys.stdin.readline
n = int(input())
par = [-1] + [int(i) - 1 for i in input().split()]
child = [[] for i in range(n)]
for i in range(1, n):
child[par[i]].append(i)
size = [1] * n
def dfs():
stack = [0]
visit = [False] * n
while stack:
u = stack[-1]
if not visit[u]:
for v in child[u]:
stack.append(v)
visit[u] = True
else:
for v in child[u]:
size[u] += size[v]
stack.pop()
ans = [0] * n
ans[0] = 1
def dfs2():
stack = [0]
while stack:
u = stack.pop()
sm = 0
for v in child[u]:
sm += size[v]
for v in child[u]:
ans[v] = (sm - size[v]) * 0.5 + 1 + ans[u]
stack.append(v)
dfs()
dfs2()
print(*ans)
```
| 84,662 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Harry Water, Ronaldo, Her-my-oh-knee and their friends have started a new school year at their MDCS School of Speechcraft and Misery. At the time, they are very happy to have seen each other after a long time. The sun is shining, birds are singing, flowers are blooming, and their Potions class teacher, professor Snipe is sulky as usual. Due to his angst fueled by disappointment in his own life, he has given them a lot of homework in Potions class.
Each of the n students has been assigned a single task. Some students do certain tasks faster than others. Thus, they want to redistribute the tasks so that each student still does exactly one task, and that all tasks are finished. Each student has their own laziness level, and each task has its own difficulty level. Professor Snipe is trying hard to improve their work ethics, so each studentβs laziness level is equal to their taskβs difficulty level. Both sets of values are given by the sequence a, where ai represents both the laziness level of the i-th student and the difficulty of his task.
The time a student needs to finish a task is equal to the product of their laziness level and the taskβs difficulty. They are wondering, what is the minimum possible total time they must spend to finish all tasks if they distribute them in the optimal way. Each person should receive one task and each task should be given to one person. Print the answer modulo 10 007.
Input
The first line of input contains integer n (1 β€ n β€ 100 000) β the number of tasks. The next n lines contain exactly one integer number ai (1 β€ ai β€ 100 000) β both the difficulty of the initial task and the laziness of the i-th students.
Output
Print the minimum total time to finish all tasks modulo 10 007.
Example
Input
2
1
3
Output
6
Note
In the first sample, if the students switch their tasks, they will be able to finish them in 3 + 3 = 6 time units.
Tags: implementation, sortings
Correct Solution:
```
n=int(input())
l=[]
for i in range(n):
x=int(input())
l.append(x)
l.sort()
s=0
for i in range(n):
s+=l[i]*l[n-i-1]
print(s%10007)
```
| 84,663 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Harry Water, Ronaldo, Her-my-oh-knee and their friends have started a new school year at their MDCS School of Speechcraft and Misery. At the time, they are very happy to have seen each other after a long time. The sun is shining, birds are singing, flowers are blooming, and their Potions class teacher, professor Snipe is sulky as usual. Due to his angst fueled by disappointment in his own life, he has given them a lot of homework in Potions class.
Each of the n students has been assigned a single task. Some students do certain tasks faster than others. Thus, they want to redistribute the tasks so that each student still does exactly one task, and that all tasks are finished. Each student has their own laziness level, and each task has its own difficulty level. Professor Snipe is trying hard to improve their work ethics, so each studentβs laziness level is equal to their taskβs difficulty level. Both sets of values are given by the sequence a, where ai represents both the laziness level of the i-th student and the difficulty of his task.
The time a student needs to finish a task is equal to the product of their laziness level and the taskβs difficulty. They are wondering, what is the minimum possible total time they must spend to finish all tasks if they distribute them in the optimal way. Each person should receive one task and each task should be given to one person. Print the answer modulo 10 007.
Input
The first line of input contains integer n (1 β€ n β€ 100 000) β the number of tasks. The next n lines contain exactly one integer number ai (1 β€ ai β€ 100 000) β both the difficulty of the initial task and the laziness of the i-th students.
Output
Print the minimum total time to finish all tasks modulo 10 007.
Example
Input
2
1
3
Output
6
Note
In the first sample, if the students switch their tasks, they will be able to finish them in 3 + 3 = 6 time units.
Tags: implementation, sortings
Correct Solution:
```
n=int(input())
l=[]
for i in range(n):
l.append(int(input()))
l.sort()
r=l[:];
r.reverse()
res=0;
for i in range(n):
res=(res+l[i]*r[i])%10007
print(res)
```
| 84,664 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Harry Water, Ronaldo, Her-my-oh-knee and their friends have started a new school year at their MDCS School of Speechcraft and Misery. At the time, they are very happy to have seen each other after a long time. The sun is shining, birds are singing, flowers are blooming, and their Potions class teacher, professor Snipe is sulky as usual. Due to his angst fueled by disappointment in his own life, he has given them a lot of homework in Potions class.
Each of the n students has been assigned a single task. Some students do certain tasks faster than others. Thus, they want to redistribute the tasks so that each student still does exactly one task, and that all tasks are finished. Each student has their own laziness level, and each task has its own difficulty level. Professor Snipe is trying hard to improve their work ethics, so each studentβs laziness level is equal to their taskβs difficulty level. Both sets of values are given by the sequence a, where ai represents both the laziness level of the i-th student and the difficulty of his task.
The time a student needs to finish a task is equal to the product of their laziness level and the taskβs difficulty. They are wondering, what is the minimum possible total time they must spend to finish all tasks if they distribute them in the optimal way. Each person should receive one task and each task should be given to one person. Print the answer modulo 10 007.
Input
The first line of input contains integer n (1 β€ n β€ 100 000) β the number of tasks. The next n lines contain exactly one integer number ai (1 β€ ai β€ 100 000) β both the difficulty of the initial task and the laziness of the i-th students.
Output
Print the minimum total time to finish all tasks modulo 10 007.
Example
Input
2
1
3
Output
6
Note
In the first sample, if the students switch their tasks, they will be able to finish them in 3 + 3 = 6 time units.
Tags: implementation, sortings
Correct Solution:
```
n = int(input())
lazy = []
tasks = []
for x in range(n):
k = int(input())
lazy.append(k)
tasks.append(k)
lazy.sort()
tasks.sort(reverse = True)
thing = list(zip(lazy, tasks))
total = 0
for x in thing:
total += x[0] * x[1]
print(int(total%10007))
```
| 84,665 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Harry Water, Ronaldo, Her-my-oh-knee and their friends have started a new school year at their MDCS School of Speechcraft and Misery. At the time, they are very happy to have seen each other after a long time. The sun is shining, birds are singing, flowers are blooming, and their Potions class teacher, professor Snipe is sulky as usual. Due to his angst fueled by disappointment in his own life, he has given them a lot of homework in Potions class.
Each of the n students has been assigned a single task. Some students do certain tasks faster than others. Thus, they want to redistribute the tasks so that each student still does exactly one task, and that all tasks are finished. Each student has their own laziness level, and each task has its own difficulty level. Professor Snipe is trying hard to improve their work ethics, so each studentβs laziness level is equal to their taskβs difficulty level. Both sets of values are given by the sequence a, where ai represents both the laziness level of the i-th student and the difficulty of his task.
The time a student needs to finish a task is equal to the product of their laziness level and the taskβs difficulty. They are wondering, what is the minimum possible total time they must spend to finish all tasks if they distribute them in the optimal way. Each person should receive one task and each task should be given to one person. Print the answer modulo 10 007.
Input
The first line of input contains integer n (1 β€ n β€ 100 000) β the number of tasks. The next n lines contain exactly one integer number ai (1 β€ ai β€ 100 000) β both the difficulty of the initial task and the laziness of the i-th students.
Output
Print the minimum total time to finish all tasks modulo 10 007.
Example
Input
2
1
3
Output
6
Note
In the first sample, if the students switch their tasks, they will be able to finish them in 3 + 3 = 6 time units.
Tags: implementation, sortings
Correct Solution:
```
n = int(input())
dt = sorted([int(input()) for i in range(n)])
ans = 0
for i in range(n):
ans += dt[i] * dt[-i-1]
print(ans%10007)
```
| 84,666 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Harry Water, Ronaldo, Her-my-oh-knee and their friends have started a new school year at their MDCS School of Speechcraft and Misery. At the time, they are very happy to have seen each other after a long time. The sun is shining, birds are singing, flowers are blooming, and their Potions class teacher, professor Snipe is sulky as usual. Due to his angst fueled by disappointment in his own life, he has given them a lot of homework in Potions class.
Each of the n students has been assigned a single task. Some students do certain tasks faster than others. Thus, they want to redistribute the tasks so that each student still does exactly one task, and that all tasks are finished. Each student has their own laziness level, and each task has its own difficulty level. Professor Snipe is trying hard to improve their work ethics, so each studentβs laziness level is equal to their taskβs difficulty level. Both sets of values are given by the sequence a, where ai represents both the laziness level of the i-th student and the difficulty of his task.
The time a student needs to finish a task is equal to the product of their laziness level and the taskβs difficulty. They are wondering, what is the minimum possible total time they must spend to finish all tasks if they distribute them in the optimal way. Each person should receive one task and each task should be given to one person. Print the answer modulo 10 007.
Input
The first line of input contains integer n (1 β€ n β€ 100 000) β the number of tasks. The next n lines contain exactly one integer number ai (1 β€ ai β€ 100 000) β both the difficulty of the initial task and the laziness of the i-th students.
Output
Print the minimum total time to finish all tasks modulo 10 007.
Example
Input
2
1
3
Output
6
Note
In the first sample, if the students switch their tasks, they will be able to finish them in 3 + 3 = 6 time units.
Tags: implementation, sortings
Correct Solution:
```
n = int(input())
a = sorted([int(input()) for i in range(n)])
time = 0
for i in range(n):
time += a[i] * a[n - 1 - i]
print(time % 10007)
```
| 84,667 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Harry Water, Ronaldo, Her-my-oh-knee and their friends have started a new school year at their MDCS School of Speechcraft and Misery. At the time, they are very happy to have seen each other after a long time. The sun is shining, birds are singing, flowers are blooming, and their Potions class teacher, professor Snipe is sulky as usual. Due to his angst fueled by disappointment in his own life, he has given them a lot of homework in Potions class.
Each of the n students has been assigned a single task. Some students do certain tasks faster than others. Thus, they want to redistribute the tasks so that each student still does exactly one task, and that all tasks are finished. Each student has their own laziness level, and each task has its own difficulty level. Professor Snipe is trying hard to improve their work ethics, so each studentβs laziness level is equal to their taskβs difficulty level. Both sets of values are given by the sequence a, where ai represents both the laziness level of the i-th student and the difficulty of his task.
The time a student needs to finish a task is equal to the product of their laziness level and the taskβs difficulty. They are wondering, what is the minimum possible total time they must spend to finish all tasks if they distribute them in the optimal way. Each person should receive one task and each task should be given to one person. Print the answer modulo 10 007.
Input
The first line of input contains integer n (1 β€ n β€ 100 000) β the number of tasks. The next n lines contain exactly one integer number ai (1 β€ ai β€ 100 000) β both the difficulty of the initial task and the laziness of the i-th students.
Output
Print the minimum total time to finish all tasks modulo 10 007.
Example
Input
2
1
3
Output
6
Note
In the first sample, if the students switch their tasks, they will be able to finish them in 3 + 3 = 6 time units.
Tags: implementation, sortings
Correct Solution:
```
n=int(input())
a=[]
for i in range(n):
a.append(int(input()))
a.sort()
p1=0
p2=n-1
t=0
while p1<p2:
t+=a[p1]*a[p2]
p1+=1
p2-=1
t*=2
if n%2==1:
t+=a[n//2]**2
print(t%10007)
```
| 84,668 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Harry Water, Ronaldo, Her-my-oh-knee and their friends have started a new school year at their MDCS School of Speechcraft and Misery. At the time, they are very happy to have seen each other after a long time. The sun is shining, birds are singing, flowers are blooming, and their Potions class teacher, professor Snipe is sulky as usual. Due to his angst fueled by disappointment in his own life, he has given them a lot of homework in Potions class.
Each of the n students has been assigned a single task. Some students do certain tasks faster than others. Thus, they want to redistribute the tasks so that each student still does exactly one task, and that all tasks are finished. Each student has their own laziness level, and each task has its own difficulty level. Professor Snipe is trying hard to improve their work ethics, so each studentβs laziness level is equal to their taskβs difficulty level. Both sets of values are given by the sequence a, where ai represents both the laziness level of the i-th student and the difficulty of his task.
The time a student needs to finish a task is equal to the product of their laziness level and the taskβs difficulty. They are wondering, what is the minimum possible total time they must spend to finish all tasks if they distribute them in the optimal way. Each person should receive one task and each task should be given to one person. Print the answer modulo 10 007.
Input
The first line of input contains integer n (1 β€ n β€ 100 000) β the number of tasks. The next n lines contain exactly one integer number ai (1 β€ ai β€ 100 000) β both the difficulty of the initial task and the laziness of the i-th students.
Output
Print the minimum total time to finish all tasks modulo 10 007.
Example
Input
2
1
3
Output
6
Note
In the first sample, if the students switch their tasks, they will be able to finish them in 3 + 3 = 6 time units.
Tags: implementation, sortings
Correct Solution:
```
n=int(input())
a = []
for _ in range(n):
a.append(int(input()))
a = sorted(a)
b = sorted(a, reverse=True)
print (sum([i*j for i,j in zip(a,b)]) % 10007)
```
| 84,669 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Harry Water, Ronaldo, Her-my-oh-knee and their friends have started a new school year at their MDCS School of Speechcraft and Misery. At the time, they are very happy to have seen each other after a long time. The sun is shining, birds are singing, flowers are blooming, and their Potions class teacher, professor Snipe is sulky as usual. Due to his angst fueled by disappointment in his own life, he has given them a lot of homework in Potions class.
Each of the n students has been assigned a single task. Some students do certain tasks faster than others. Thus, they want to redistribute the tasks so that each student still does exactly one task, and that all tasks are finished. Each student has their own laziness level, and each task has its own difficulty level. Professor Snipe is trying hard to improve their work ethics, so each studentβs laziness level is equal to their taskβs difficulty level. Both sets of values are given by the sequence a, where ai represents both the laziness level of the i-th student and the difficulty of his task.
The time a student needs to finish a task is equal to the product of their laziness level and the taskβs difficulty. They are wondering, what is the minimum possible total time they must spend to finish all tasks if they distribute them in the optimal way. Each person should receive one task and each task should be given to one person. Print the answer modulo 10 007.
Input
The first line of input contains integer n (1 β€ n β€ 100 000) β the number of tasks. The next n lines contain exactly one integer number ai (1 β€ ai β€ 100 000) β both the difficulty of the initial task and the laziness of the i-th students.
Output
Print the minimum total time to finish all tasks modulo 10 007.
Example
Input
2
1
3
Output
6
Note
In the first sample, if the students switch their tasks, they will be able to finish them in 3 + 3 = 6 time units.
Tags: implementation, sortings
Correct Solution:
```
# link: https://codeforces.com/problemset/problem/717/C
from sys import stdin, stdout
if __name__ == "__main__":
n = int(stdin.readline())
difficulties = [0] * (n)
for i in range(n):
difficulties[i] = int(stdin.readline())
difficulties.sort()
start = 0
end = n-1
result = 0
while start < n:
result += (difficulties[start] * difficulties[end])
start += 1
end -= 1
print(result % 10007)
```
| 84,670 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Harry Water, Ronaldo, Her-my-oh-knee and their friends have started a new school year at their MDCS School of Speechcraft and Misery. At the time, they are very happy to have seen each other after a long time. The sun is shining, birds are singing, flowers are blooming, and their Potions class teacher, professor Snipe is sulky as usual. Due to his angst fueled by disappointment in his own life, he has given them a lot of homework in Potions class.
Each of the n students has been assigned a single task. Some students do certain tasks faster than others. Thus, they want to redistribute the tasks so that each student still does exactly one task, and that all tasks are finished. Each student has their own laziness level, and each task has its own difficulty level. Professor Snipe is trying hard to improve their work ethics, so each studentβs laziness level is equal to their taskβs difficulty level. Both sets of values are given by the sequence a, where ai represents both the laziness level of the i-th student and the difficulty of his task.
The time a student needs to finish a task is equal to the product of their laziness level and the taskβs difficulty. They are wondering, what is the minimum possible total time they must spend to finish all tasks if they distribute them in the optimal way. Each person should receive one task and each task should be given to one person. Print the answer modulo 10 007.
Input
The first line of input contains integer n (1 β€ n β€ 100 000) β the number of tasks. The next n lines contain exactly one integer number ai (1 β€ ai β€ 100 000) β both the difficulty of the initial task and the laziness of the i-th students.
Output
Print the minimum total time to finish all tasks modulo 10 007.
Example
Input
2
1
3
Output
6
Note
In the first sample, if the students switch their tasks, they will be able to finish them in 3 + 3 = 6 time units.
Submitted Solution:
```
import math
from collections import *
from heapq import *
def intlist():
return list(map(int, input().split()))
class Solution:
def solve(self):
n = int(input())
nums = [0] * n
for i in range(n):
nums[i] = int(input())
ans = 0
nums.sort()
for i in range(n):
ans += nums[i] * nums[-(i + 1)]
return ans % 10007
aa = Solution()
def go(x=1):
for _ in range(x):
print((aa.solve()))
go()
```
Yes
| 84,671 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Harry Water, Ronaldo, Her-my-oh-knee and their friends have started a new school year at their MDCS School of Speechcraft and Misery. At the time, they are very happy to have seen each other after a long time. The sun is shining, birds are singing, flowers are blooming, and their Potions class teacher, professor Snipe is sulky as usual. Due to his angst fueled by disappointment in his own life, he has given them a lot of homework in Potions class.
Each of the n students has been assigned a single task. Some students do certain tasks faster than others. Thus, they want to redistribute the tasks so that each student still does exactly one task, and that all tasks are finished. Each student has their own laziness level, and each task has its own difficulty level. Professor Snipe is trying hard to improve their work ethics, so each studentβs laziness level is equal to their taskβs difficulty level. Both sets of values are given by the sequence a, where ai represents both the laziness level of the i-th student and the difficulty of his task.
The time a student needs to finish a task is equal to the product of their laziness level and the taskβs difficulty. They are wondering, what is the minimum possible total time they must spend to finish all tasks if they distribute them in the optimal way. Each person should receive one task and each task should be given to one person. Print the answer modulo 10 007.
Input
The first line of input contains integer n (1 β€ n β€ 100 000) β the number of tasks. The next n lines contain exactly one integer number ai (1 β€ ai β€ 100 000) β both the difficulty of the initial task and the laziness of the i-th students.
Output
Print the minimum total time to finish all tasks modulo 10 007.
Example
Input
2
1
3
Output
6
Note
In the first sample, if the students switch their tasks, they will be able to finish them in 3 + 3 = 6 time units.
Submitted Solution:
```
n = int(input())
A = [0] * n
for i in range(n):
per = int(input())
A[i] = per
A.sort()
answer = 0
for i in range(n):
answer = (answer + A[i] * A[n - i - 1]) % 10007
print(answer)
```
Yes
| 84,672 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Harry Water, Ronaldo, Her-my-oh-knee and their friends have started a new school year at their MDCS School of Speechcraft and Misery. At the time, they are very happy to have seen each other after a long time. The sun is shining, birds are singing, flowers are blooming, and their Potions class teacher, professor Snipe is sulky as usual. Due to his angst fueled by disappointment in his own life, he has given them a lot of homework in Potions class.
Each of the n students has been assigned a single task. Some students do certain tasks faster than others. Thus, they want to redistribute the tasks so that each student still does exactly one task, and that all tasks are finished. Each student has their own laziness level, and each task has its own difficulty level. Professor Snipe is trying hard to improve their work ethics, so each studentβs laziness level is equal to their taskβs difficulty level. Both sets of values are given by the sequence a, where ai represents both the laziness level of the i-th student and the difficulty of his task.
The time a student needs to finish a task is equal to the product of their laziness level and the taskβs difficulty. They are wondering, what is the minimum possible total time they must spend to finish all tasks if they distribute them in the optimal way. Each person should receive one task and each task should be given to one person. Print the answer modulo 10 007.
Input
The first line of input contains integer n (1 β€ n β€ 100 000) β the number of tasks. The next n lines contain exactly one integer number ai (1 β€ ai β€ 100 000) β both the difficulty of the initial task and the laziness of the i-th students.
Output
Print the minimum total time to finish all tasks modulo 10 007.
Example
Input
2
1
3
Output
6
Note
In the first sample, if the students switch their tasks, they will be able to finish them in 3 + 3 = 6 time units.
Submitted Solution:
```
#!/usr/bin/env python
#-*-coding:utf-8 -*-
n=int(input())
A=sorted(int(input())for _ in range(n))
B=10007
s=0
for i in range(n):s=(A[i]*A[-1-i]+s)%B
print(s)
```
Yes
| 84,673 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Harry Water, Ronaldo, Her-my-oh-knee and their friends have started a new school year at their MDCS School of Speechcraft and Misery. At the time, they are very happy to have seen each other after a long time. The sun is shining, birds are singing, flowers are blooming, and their Potions class teacher, professor Snipe is sulky as usual. Due to his angst fueled by disappointment in his own life, he has given them a lot of homework in Potions class.
Each of the n students has been assigned a single task. Some students do certain tasks faster than others. Thus, they want to redistribute the tasks so that each student still does exactly one task, and that all tasks are finished. Each student has their own laziness level, and each task has its own difficulty level. Professor Snipe is trying hard to improve their work ethics, so each studentβs laziness level is equal to their taskβs difficulty level. Both sets of values are given by the sequence a, where ai represents both the laziness level of the i-th student and the difficulty of his task.
The time a student needs to finish a task is equal to the product of their laziness level and the taskβs difficulty. They are wondering, what is the minimum possible total time they must spend to finish all tasks if they distribute them in the optimal way. Each person should receive one task and each task should be given to one person. Print the answer modulo 10 007.
Input
The first line of input contains integer n (1 β€ n β€ 100 000) β the number of tasks. The next n lines contain exactly one integer number ai (1 β€ ai β€ 100 000) β both the difficulty of the initial task and the laziness of the i-th students.
Output
Print the minimum total time to finish all tasks modulo 10 007.
Example
Input
2
1
3
Output
6
Note
In the first sample, if the students switch their tasks, they will be able to finish them in 3 + 3 = 6 time units.
Submitted Solution:
```
n=int(input())
array=[]
for i in range(0,n):
x=int(input())
array.append(x)
array.sort()
sum=0
for i in range(0,n):
sum=sum+array[i]*array[n-1-i]
print(sum%10007)
```
Yes
| 84,674 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Harry Water, Ronaldo, Her-my-oh-knee and their friends have started a new school year at their MDCS School of Speechcraft and Misery. At the time, they are very happy to have seen each other after a long time. The sun is shining, birds are singing, flowers are blooming, and their Potions class teacher, professor Snipe is sulky as usual. Due to his angst fueled by disappointment in his own life, he has given them a lot of homework in Potions class.
Each of the n students has been assigned a single task. Some students do certain tasks faster than others. Thus, they want to redistribute the tasks so that each student still does exactly one task, and that all tasks are finished. Each student has their own laziness level, and each task has its own difficulty level. Professor Snipe is trying hard to improve their work ethics, so each studentβs laziness level is equal to their taskβs difficulty level. Both sets of values are given by the sequence a, where ai represents both the laziness level of the i-th student and the difficulty of his task.
The time a student needs to finish a task is equal to the product of their laziness level and the taskβs difficulty. They are wondering, what is the minimum possible total time they must spend to finish all tasks if they distribute them in the optimal way. Each person should receive one task and each task should be given to one person. Print the answer modulo 10 007.
Input
The first line of input contains integer n (1 β€ n β€ 100 000) β the number of tasks. The next n lines contain exactly one integer number ai (1 β€ ai β€ 100 000) β both the difficulty of the initial task and the laziness of the i-th students.
Output
Print the minimum total time to finish all tasks modulo 10 007.
Example
Input
2
1
3
Output
6
Note
In the first sample, if the students switch their tasks, they will be able to finish them in 3 + 3 = 6 time units.
Submitted Solution:
```
n = int(input())
sp = []
for i in range(n):
sp.append(int(input()))
sp.sort()
sp1 = sp[::-1]
s = 0
for i in range(n):
s = s + sp[i] * sp1[i]
print(s)
```
No
| 84,675 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Harry Water, Ronaldo, Her-my-oh-knee and their friends have started a new school year at their MDCS School of Speechcraft and Misery. At the time, they are very happy to have seen each other after a long time. The sun is shining, birds are singing, flowers are blooming, and their Potions class teacher, professor Snipe is sulky as usual. Due to his angst fueled by disappointment in his own life, he has given them a lot of homework in Potions class.
Each of the n students has been assigned a single task. Some students do certain tasks faster than others. Thus, they want to redistribute the tasks so that each student still does exactly one task, and that all tasks are finished. Each student has their own laziness level, and each task has its own difficulty level. Professor Snipe is trying hard to improve their work ethics, so each studentβs laziness level is equal to their taskβs difficulty level. Both sets of values are given by the sequence a, where ai represents both the laziness level of the i-th student and the difficulty of his task.
The time a student needs to finish a task is equal to the product of their laziness level and the taskβs difficulty. They are wondering, what is the minimum possible total time they must spend to finish all tasks if they distribute them in the optimal way. Each person should receive one task and each task should be given to one person. Print the answer modulo 10 007.
Input
The first line of input contains integer n (1 β€ n β€ 100 000) β the number of tasks. The next n lines contain exactly one integer number ai (1 β€ ai β€ 100 000) β both the difficulty of the initial task and the laziness of the i-th students.
Output
Print the minimum total time to finish all tasks modulo 10 007.
Example
Input
2
1
3
Output
6
Note
In the first sample, if the students switch their tasks, they will be able to finish them in 3 + 3 = 6 time units.
Submitted Solution:
```
import sys
input = sys.stdin.readline
n = int(input())
tasks = []
for i in range(n):
tasks.append(int(input()))
tasks.sort()
time = 0
for i in range(n//2):
time+=(tasks[i]*tasks[-(i+1)]*2)
print(time)
```
No
| 84,676 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Harry Water, Ronaldo, Her-my-oh-knee and their friends have started a new school year at their MDCS School of Speechcraft and Misery. At the time, they are very happy to have seen each other after a long time. The sun is shining, birds are singing, flowers are blooming, and their Potions class teacher, professor Snipe is sulky as usual. Due to his angst fueled by disappointment in his own life, he has given them a lot of homework in Potions class.
Each of the n students has been assigned a single task. Some students do certain tasks faster than others. Thus, they want to redistribute the tasks so that each student still does exactly one task, and that all tasks are finished. Each student has their own laziness level, and each task has its own difficulty level. Professor Snipe is trying hard to improve their work ethics, so each studentβs laziness level is equal to their taskβs difficulty level. Both sets of values are given by the sequence a, where ai represents both the laziness level of the i-th student and the difficulty of his task.
The time a student needs to finish a task is equal to the product of their laziness level and the taskβs difficulty. They are wondering, what is the minimum possible total time they must spend to finish all tasks if they distribute them in the optimal way. Each person should receive one task and each task should be given to one person. Print the answer modulo 10 007.
Input
The first line of input contains integer n (1 β€ n β€ 100 000) β the number of tasks. The next n lines contain exactly one integer number ai (1 β€ ai β€ 100 000) β both the difficulty of the initial task and the laziness of the i-th students.
Output
Print the minimum total time to finish all tasks modulo 10 007.
Example
Input
2
1
3
Output
6
Note
In the first sample, if the students switch their tasks, they will be able to finish them in 3 + 3 = 6 time units.
Submitted Solution:
```
n=int(input())
a = []
for _ in range(n):
a.append(int(input()))
a = sorted(a)
b = sorted(a, reverse=True)
print (sum([i*j for i,j in zip(a,b)]))
```
No
| 84,677 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Harry Water, Ronaldo, Her-my-oh-knee and their friends have started a new school year at their MDCS School of Speechcraft and Misery. At the time, they are very happy to have seen each other after a long time. The sun is shining, birds are singing, flowers are blooming, and their Potions class teacher, professor Snipe is sulky as usual. Due to his angst fueled by disappointment in his own life, he has given them a lot of homework in Potions class.
Each of the n students has been assigned a single task. Some students do certain tasks faster than others. Thus, they want to redistribute the tasks so that each student still does exactly one task, and that all tasks are finished. Each student has their own laziness level, and each task has its own difficulty level. Professor Snipe is trying hard to improve their work ethics, so each studentβs laziness level is equal to their taskβs difficulty level. Both sets of values are given by the sequence a, where ai represents both the laziness level of the i-th student and the difficulty of his task.
The time a student needs to finish a task is equal to the product of their laziness level and the taskβs difficulty. They are wondering, what is the minimum possible total time they must spend to finish all tasks if they distribute them in the optimal way. Each person should receive one task and each task should be given to one person. Print the answer modulo 10 007.
Input
The first line of input contains integer n (1 β€ n β€ 100 000) β the number of tasks. The next n lines contain exactly one integer number ai (1 β€ ai β€ 100 000) β both the difficulty of the initial task and the laziness of the i-th students.
Output
Print the minimum total time to finish all tasks modulo 10 007.
Example
Input
2
1
3
Output
6
Note
In the first sample, if the students switch their tasks, they will be able to finish them in 3 + 3 = 6 time units.
Submitted Solution:
```
import sys
import string
from heapq import *
from bisect import *
from collections import Counter, defaultdict
from math import fsum, sqrt, gcd, ceil, factorial
from operator import *
from itertools import accumulate
inf = float("inf")
# input = sys.stdin.readline
flush = lambda: sys.stdout.flush
comb = lambda x, y: (factorial(x) // factorial(y)) // factorial(x - y)
en = lambda x: list(enumerate(x))
# inputs
# ip = lambda : input().rstrip()
ip = lambda: input()
ii = lambda: int(input())
r = lambda: map(int, input().split())
rr = lambda: list(r())
n = ii()
arr = [ii() for _ in range(n)]
c = 0
for i in range(n):
c = c + arr[i] * arr[n - i - 1]
print(c % 10007)
```
No
| 84,678 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Dasha logged into the system and began to solve problems. One of them is as follows:
Given two sequences a and b of length n each you need to write a sequence c of length n, the i-th element of which is calculated as follows: ci = bi - ai.
About sequences a and b we know that their elements are in the range from l to r. More formally, elements satisfy the following conditions: l β€ ai β€ r and l β€ bi β€ r. About sequence c we know that all its elements are distinct.
<image>
Dasha wrote a solution to that problem quickly, but checking her work on the standard test was not so easy. Due to an error in the test system only the sequence a and the compressed sequence of the sequence c were known from that test.
Let's give the definition to a compressed sequence. A compressed sequence of sequence c of length n is a sequence p of length n, so that pi equals to the number of integers which are less than or equal to ci in the sequence c. For example, for the sequence c = [250, 200, 300, 100, 50] the compressed sequence will be p = [4, 3, 5, 2, 1]. Pay attention that in c all integers are distinct. Consequently, the compressed sequence contains all integers from 1 to n inclusively.
Help Dasha to find any sequence b for which the calculated compressed sequence of sequence c is correct.
Input
The first line contains three integers n, l, r (1 β€ n β€ 105, 1 β€ l β€ r β€ 109) β the length of the sequence and boundaries of the segment where the elements of sequences a and b are.
The next line contains n integers a1, a2, ..., an (l β€ ai β€ r) β the elements of the sequence a.
The next line contains n distinct integers p1, p2, ..., pn (1 β€ pi β€ n) β the compressed sequence of the sequence c.
Output
If there is no the suitable sequence b, then in the only line print "-1".
Otherwise, in the only line print n integers β the elements of any suitable sequence b.
Examples
Input
5 1 5
1 1 1 1 1
3 1 5 4 2
Output
3 1 5 4 2
Input
4 2 9
3 4 8 9
3 2 1 4
Output
2 2 2 9
Input
6 1 5
1 1 1 1 1 1
2 3 5 4 1 6
Output
-1
Note
Sequence b which was found in the second sample is suitable, because calculated sequence c = [2 - 3, 2 - 4, 2 - 8, 9 - 9] = [ - 1, - 2, - 6, 0] (note that ci = bi - ai) has compressed sequence equals to p = [3, 2, 1, 4].
Tags: binary search, brute force, constructive algorithms, greedy, sortings
Correct Solution:
```
from operator import itemgetter
n, l, r = [int(i) for i in input().split()]
a = [int(i) for i in input().split()]
p = [int(i) for i in input().split()]
A = sorted([[a[i], p[i], i, 0] for i in range(n)], key = itemgetter(1))
A[0][3] = l
c = A[0][3] - A[0][0]
for i in range(1, n):
A[i][3] = max(l, A[i][0]+c+1)
c = A[i][3] - A[i][0]
if A[i][3] > r:
print(-1)
break
else:
A = sorted(A, key = itemgetter(2))
for i in range(n):
print(A[i][3], end=" ")
```
| 84,679 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Dasha logged into the system and began to solve problems. One of them is as follows:
Given two sequences a and b of length n each you need to write a sequence c of length n, the i-th element of which is calculated as follows: ci = bi - ai.
About sequences a and b we know that their elements are in the range from l to r. More formally, elements satisfy the following conditions: l β€ ai β€ r and l β€ bi β€ r. About sequence c we know that all its elements are distinct.
<image>
Dasha wrote a solution to that problem quickly, but checking her work on the standard test was not so easy. Due to an error in the test system only the sequence a and the compressed sequence of the sequence c were known from that test.
Let's give the definition to a compressed sequence. A compressed sequence of sequence c of length n is a sequence p of length n, so that pi equals to the number of integers which are less than or equal to ci in the sequence c. For example, for the sequence c = [250, 200, 300, 100, 50] the compressed sequence will be p = [4, 3, 5, 2, 1]. Pay attention that in c all integers are distinct. Consequently, the compressed sequence contains all integers from 1 to n inclusively.
Help Dasha to find any sequence b for which the calculated compressed sequence of sequence c is correct.
Input
The first line contains three integers n, l, r (1 β€ n β€ 105, 1 β€ l β€ r β€ 109) β the length of the sequence and boundaries of the segment where the elements of sequences a and b are.
The next line contains n integers a1, a2, ..., an (l β€ ai β€ r) β the elements of the sequence a.
The next line contains n distinct integers p1, p2, ..., pn (1 β€ pi β€ n) β the compressed sequence of the sequence c.
Output
If there is no the suitable sequence b, then in the only line print "-1".
Otherwise, in the only line print n integers β the elements of any suitable sequence b.
Examples
Input
5 1 5
1 1 1 1 1
3 1 5 4 2
Output
3 1 5 4 2
Input
4 2 9
3 4 8 9
3 2 1 4
Output
2 2 2 9
Input
6 1 5
1 1 1 1 1 1
2 3 5 4 1 6
Output
-1
Note
Sequence b which was found in the second sample is suitable, because calculated sequence c = [2 - 3, 2 - 4, 2 - 8, 9 - 9] = [ - 1, - 2, - 6, 0] (note that ci = bi - ai) has compressed sequence equals to p = [3, 2, 1, 4].
Tags: binary search, brute force, constructive algorithms, greedy, sortings
Correct Solution:
```
n, l, r = map(int, input().split())
a = list(map(int, input().split()))
p = list(map(int, input().split()))
seg = [0] * n
for i in range(n):
seg[i] = [l - a[i], r - a[i]]
segments = [0] * n
for i in range(n):
segments[p[i] - 1] = seg[i]
c = [0] * n
can = True
l = -(10 ** 18)
for i in range(n):
if l >= segments[i][1]:
can = False
break
if segments[i][0] > l:
l = segments[i][0]
else:
l = l + 1
c[i] = l
if not can:
print(-1)
else:
for i in range(n):
print(c[p[i] - 1] + a[i], end = ' ')
```
| 84,680 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Dasha logged into the system and began to solve problems. One of them is as follows:
Given two sequences a and b of length n each you need to write a sequence c of length n, the i-th element of which is calculated as follows: ci = bi - ai.
About sequences a and b we know that their elements are in the range from l to r. More formally, elements satisfy the following conditions: l β€ ai β€ r and l β€ bi β€ r. About sequence c we know that all its elements are distinct.
<image>
Dasha wrote a solution to that problem quickly, but checking her work on the standard test was not so easy. Due to an error in the test system only the sequence a and the compressed sequence of the sequence c were known from that test.
Let's give the definition to a compressed sequence. A compressed sequence of sequence c of length n is a sequence p of length n, so that pi equals to the number of integers which are less than or equal to ci in the sequence c. For example, for the sequence c = [250, 200, 300, 100, 50] the compressed sequence will be p = [4, 3, 5, 2, 1]. Pay attention that in c all integers are distinct. Consequently, the compressed sequence contains all integers from 1 to n inclusively.
Help Dasha to find any sequence b for which the calculated compressed sequence of sequence c is correct.
Input
The first line contains three integers n, l, r (1 β€ n β€ 105, 1 β€ l β€ r β€ 109) β the length of the sequence and boundaries of the segment where the elements of sequences a and b are.
The next line contains n integers a1, a2, ..., an (l β€ ai β€ r) β the elements of the sequence a.
The next line contains n distinct integers p1, p2, ..., pn (1 β€ pi β€ n) β the compressed sequence of the sequence c.
Output
If there is no the suitable sequence b, then in the only line print "-1".
Otherwise, in the only line print n integers β the elements of any suitable sequence b.
Examples
Input
5 1 5
1 1 1 1 1
3 1 5 4 2
Output
3 1 5 4 2
Input
4 2 9
3 4 8 9
3 2 1 4
Output
2 2 2 9
Input
6 1 5
1 1 1 1 1 1
2 3 5 4 1 6
Output
-1
Note
Sequence b which was found in the second sample is suitable, because calculated sequence c = [2 - 3, 2 - 4, 2 - 8, 9 - 9] = [ - 1, - 2, - 6, 0] (note that ci = bi - ai) has compressed sequence equals to p = [3, 2, 1, 4].
Tags: binary search, brute force, constructive algorithms, greedy, sortings
Correct Solution:
```
f = lambda: map(int, input().split())
n, l, r = f()
b = [x + y for x, y in zip(f(), f())]
u, v = l - min(b), r - max(b)
print(-1 if u > v else ' '.join(str(q + u) for q in b))
```
| 84,681 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Dasha logged into the system and began to solve problems. One of them is as follows:
Given two sequences a and b of length n each you need to write a sequence c of length n, the i-th element of which is calculated as follows: ci = bi - ai.
About sequences a and b we know that their elements are in the range from l to r. More formally, elements satisfy the following conditions: l β€ ai β€ r and l β€ bi β€ r. About sequence c we know that all its elements are distinct.
<image>
Dasha wrote a solution to that problem quickly, but checking her work on the standard test was not so easy. Due to an error in the test system only the sequence a and the compressed sequence of the sequence c were known from that test.
Let's give the definition to a compressed sequence. A compressed sequence of sequence c of length n is a sequence p of length n, so that pi equals to the number of integers which are less than or equal to ci in the sequence c. For example, for the sequence c = [250, 200, 300, 100, 50] the compressed sequence will be p = [4, 3, 5, 2, 1]. Pay attention that in c all integers are distinct. Consequently, the compressed sequence contains all integers from 1 to n inclusively.
Help Dasha to find any sequence b for which the calculated compressed sequence of sequence c is correct.
Input
The first line contains three integers n, l, r (1 β€ n β€ 105, 1 β€ l β€ r β€ 109) β the length of the sequence and boundaries of the segment where the elements of sequences a and b are.
The next line contains n integers a1, a2, ..., an (l β€ ai β€ r) β the elements of the sequence a.
The next line contains n distinct integers p1, p2, ..., pn (1 β€ pi β€ n) β the compressed sequence of the sequence c.
Output
If there is no the suitable sequence b, then in the only line print "-1".
Otherwise, in the only line print n integers β the elements of any suitable sequence b.
Examples
Input
5 1 5
1 1 1 1 1
3 1 5 4 2
Output
3 1 5 4 2
Input
4 2 9
3 4 8 9
3 2 1 4
Output
2 2 2 9
Input
6 1 5
1 1 1 1 1 1
2 3 5 4 1 6
Output
-1
Note
Sequence b which was found in the second sample is suitable, because calculated sequence c = [2 - 3, 2 - 4, 2 - 8, 9 - 9] = [ - 1, - 2, - 6, 0] (note that ci = bi - ai) has compressed sequence equals to p = [3, 2, 1, 4].
Tags: binary search, brute force, constructive algorithms, greedy, sortings
Correct Solution:
```
n,l,r=map(int,input().split())
a=[int(i) for i in input().split()]
p=[int(i) for i in input().split()]
#p is compressed form of c
b=[a[i]+p[i] for i in range(n)]
m1=min(b)
m2=max(b)
if r-l+1<m2-m1+1:
print(-1)
exit()
if l<=m1<=m2<=r:
print(*b)
exit()
if l>m1 and r<m2:
print(-1)
exit()
if l>m1:
req=l-m1
b=[i+req for i in b]
print(*b)
exit()
if r<m2:
sub=m2-r
b=[i-sub for i in b]
print(*b)
exit()
print(-1)
```
| 84,682 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Dasha logged into the system and began to solve problems. One of them is as follows:
Given two sequences a and b of length n each you need to write a sequence c of length n, the i-th element of which is calculated as follows: ci = bi - ai.
About sequences a and b we know that their elements are in the range from l to r. More formally, elements satisfy the following conditions: l β€ ai β€ r and l β€ bi β€ r. About sequence c we know that all its elements are distinct.
<image>
Dasha wrote a solution to that problem quickly, but checking her work on the standard test was not so easy. Due to an error in the test system only the sequence a and the compressed sequence of the sequence c were known from that test.
Let's give the definition to a compressed sequence. A compressed sequence of sequence c of length n is a sequence p of length n, so that pi equals to the number of integers which are less than or equal to ci in the sequence c. For example, for the sequence c = [250, 200, 300, 100, 50] the compressed sequence will be p = [4, 3, 5, 2, 1]. Pay attention that in c all integers are distinct. Consequently, the compressed sequence contains all integers from 1 to n inclusively.
Help Dasha to find any sequence b for which the calculated compressed sequence of sequence c is correct.
Input
The first line contains three integers n, l, r (1 β€ n β€ 105, 1 β€ l β€ r β€ 109) β the length of the sequence and boundaries of the segment where the elements of sequences a and b are.
The next line contains n integers a1, a2, ..., an (l β€ ai β€ r) β the elements of the sequence a.
The next line contains n distinct integers p1, p2, ..., pn (1 β€ pi β€ n) β the compressed sequence of the sequence c.
Output
If there is no the suitable sequence b, then in the only line print "-1".
Otherwise, in the only line print n integers β the elements of any suitable sequence b.
Examples
Input
5 1 5
1 1 1 1 1
3 1 5 4 2
Output
3 1 5 4 2
Input
4 2 9
3 4 8 9
3 2 1 4
Output
2 2 2 9
Input
6 1 5
1 1 1 1 1 1
2 3 5 4 1 6
Output
-1
Note
Sequence b which was found in the second sample is suitable, because calculated sequence c = [2 - 3, 2 - 4, 2 - 8, 9 - 9] = [ - 1, - 2, - 6, 0] (note that ci = bi - ai) has compressed sequence equals to p = [3, 2, 1, 4].
Tags: binary search, brute force, constructive algorithms, greedy, sortings
Correct Solution:
```
n, l, r = map(int, input().split())
a = map(int, input().split())
p = map(int, input().split())
b = list(map(lambda x: sum(x), zip(a,p)))
minb = min(b)
maxb = max(b)
if maxb - minb > r - l:
print(-1)
else:
print(' '.join(str(i-minb+l) for i in b))
```
| 84,683 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Dasha logged into the system and began to solve problems. One of them is as follows:
Given two sequences a and b of length n each you need to write a sequence c of length n, the i-th element of which is calculated as follows: ci = bi - ai.
About sequences a and b we know that their elements are in the range from l to r. More formally, elements satisfy the following conditions: l β€ ai β€ r and l β€ bi β€ r. About sequence c we know that all its elements are distinct.
<image>
Dasha wrote a solution to that problem quickly, but checking her work on the standard test was not so easy. Due to an error in the test system only the sequence a and the compressed sequence of the sequence c were known from that test.
Let's give the definition to a compressed sequence. A compressed sequence of sequence c of length n is a sequence p of length n, so that pi equals to the number of integers which are less than or equal to ci in the sequence c. For example, for the sequence c = [250, 200, 300, 100, 50] the compressed sequence will be p = [4, 3, 5, 2, 1]. Pay attention that in c all integers are distinct. Consequently, the compressed sequence contains all integers from 1 to n inclusively.
Help Dasha to find any sequence b for which the calculated compressed sequence of sequence c is correct.
Input
The first line contains three integers n, l, r (1 β€ n β€ 105, 1 β€ l β€ r β€ 109) β the length of the sequence and boundaries of the segment where the elements of sequences a and b are.
The next line contains n integers a1, a2, ..., an (l β€ ai β€ r) β the elements of the sequence a.
The next line contains n distinct integers p1, p2, ..., pn (1 β€ pi β€ n) β the compressed sequence of the sequence c.
Output
If there is no the suitable sequence b, then in the only line print "-1".
Otherwise, in the only line print n integers β the elements of any suitable sequence b.
Examples
Input
5 1 5
1 1 1 1 1
3 1 5 4 2
Output
3 1 5 4 2
Input
4 2 9
3 4 8 9
3 2 1 4
Output
2 2 2 9
Input
6 1 5
1 1 1 1 1 1
2 3 5 4 1 6
Output
-1
Note
Sequence b which was found in the second sample is suitable, because calculated sequence c = [2 - 3, 2 - 4, 2 - 8, 9 - 9] = [ - 1, - 2, - 6, 0] (note that ci = bi - ai) has compressed sequence equals to p = [3, 2, 1, 4].
Tags: binary search, brute force, constructive algorithms, greedy, sortings
Correct Solution:
```
import sys
N, L, R = map(int, input().split())
a = list(map(int, input().split()))
b = [0] * N
c = list(map(int, input().split()))
d = [i for i in range(N)]
z = [list(t) for t in zip(c, a, b, d)]
z = sorted(z)
z[0][2] = L
last = z[0][2] - z[0][1]
for i in range(1, N):
z[i][2] = max(last + 1 + z[i][1], L)
if z[i][2] > R:
print(-1)
sys.exit()
last = z[i][2] - z[i][1]
z = sorted(z, key=lambda t: t[3])
_, _, res, _ = zip(*z)
print(*res)
```
| 84,684 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Dasha logged into the system and began to solve problems. One of them is as follows:
Given two sequences a and b of length n each you need to write a sequence c of length n, the i-th element of which is calculated as follows: ci = bi - ai.
About sequences a and b we know that their elements are in the range from l to r. More formally, elements satisfy the following conditions: l β€ ai β€ r and l β€ bi β€ r. About sequence c we know that all its elements are distinct.
<image>
Dasha wrote a solution to that problem quickly, but checking her work on the standard test was not so easy. Due to an error in the test system only the sequence a and the compressed sequence of the sequence c were known from that test.
Let's give the definition to a compressed sequence. A compressed sequence of sequence c of length n is a sequence p of length n, so that pi equals to the number of integers which are less than or equal to ci in the sequence c. For example, for the sequence c = [250, 200, 300, 100, 50] the compressed sequence will be p = [4, 3, 5, 2, 1]. Pay attention that in c all integers are distinct. Consequently, the compressed sequence contains all integers from 1 to n inclusively.
Help Dasha to find any sequence b for which the calculated compressed sequence of sequence c is correct.
Input
The first line contains three integers n, l, r (1 β€ n β€ 105, 1 β€ l β€ r β€ 109) β the length of the sequence and boundaries of the segment where the elements of sequences a and b are.
The next line contains n integers a1, a2, ..., an (l β€ ai β€ r) β the elements of the sequence a.
The next line contains n distinct integers p1, p2, ..., pn (1 β€ pi β€ n) β the compressed sequence of the sequence c.
Output
If there is no the suitable sequence b, then in the only line print "-1".
Otherwise, in the only line print n integers β the elements of any suitable sequence b.
Examples
Input
5 1 5
1 1 1 1 1
3 1 5 4 2
Output
3 1 5 4 2
Input
4 2 9
3 4 8 9
3 2 1 4
Output
2 2 2 9
Input
6 1 5
1 1 1 1 1 1
2 3 5 4 1 6
Output
-1
Note
Sequence b which was found in the second sample is suitable, because calculated sequence c = [2 - 3, 2 - 4, 2 - 8, 9 - 9] = [ - 1, - 2, - 6, 0] (note that ci = bi - ai) has compressed sequence equals to p = [3, 2, 1, 4].
Tags: binary search, brute force, constructive algorithms, greedy, sortings
Correct Solution:
```
import math, re, itertools as it;prime = lambda n: len([i for i in range(2, int(math.sqrt(n) + 1)) if n % i == 0]) == 0;gcd = lambda a, b: gcd(b, a % b) if b else a;fact = lambda x: x * fact(x - 1) if x else 1;bino = lambda n, k: fact(n) / fact(k) / fact(n - k);fib11 = lambda n: 1 if n < 2 else fib11(n - 1) + fib11(n - 2);fib01 = lambda n: 0 if n == 0 else 1 if n == 1 else fib01(n - 1) + fib01(n - 2);sumofd = lambda x: x if x < 10 else sumofd(x // 10) + x % 10
n, l, r = map(int, input().split(' '))
a = list(map(int, input().split(' ')))
p = list(map(int, input().split(' ')))
dd = []
for i in range(len(a)):
dd.append([p[i], a[i]])
dd.sort(key = lambda x: -x[0])
b = []
b.append(r)
f = True
for i in range(1, n):
b.append(min(dd[i][1] + b[i - 1] - dd[i - 1][1] - 1, r))
if b[-1] < l:
f = False
break
if f:
for i in range(n):
print(b[dd[p[i] - 1][0] - 1], end = ' ')
else:
print(-1)
```
| 84,685 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Dasha logged into the system and began to solve problems. One of them is as follows:
Given two sequences a and b of length n each you need to write a sequence c of length n, the i-th element of which is calculated as follows: ci = bi - ai.
About sequences a and b we know that their elements are in the range from l to r. More formally, elements satisfy the following conditions: l β€ ai β€ r and l β€ bi β€ r. About sequence c we know that all its elements are distinct.
<image>
Dasha wrote a solution to that problem quickly, but checking her work on the standard test was not so easy. Due to an error in the test system only the sequence a and the compressed sequence of the sequence c were known from that test.
Let's give the definition to a compressed sequence. A compressed sequence of sequence c of length n is a sequence p of length n, so that pi equals to the number of integers which are less than or equal to ci in the sequence c. For example, for the sequence c = [250, 200, 300, 100, 50] the compressed sequence will be p = [4, 3, 5, 2, 1]. Pay attention that in c all integers are distinct. Consequently, the compressed sequence contains all integers from 1 to n inclusively.
Help Dasha to find any sequence b for which the calculated compressed sequence of sequence c is correct.
Input
The first line contains three integers n, l, r (1 β€ n β€ 105, 1 β€ l β€ r β€ 109) β the length of the sequence and boundaries of the segment where the elements of sequences a and b are.
The next line contains n integers a1, a2, ..., an (l β€ ai β€ r) β the elements of the sequence a.
The next line contains n distinct integers p1, p2, ..., pn (1 β€ pi β€ n) β the compressed sequence of the sequence c.
Output
If there is no the suitable sequence b, then in the only line print "-1".
Otherwise, in the only line print n integers β the elements of any suitable sequence b.
Examples
Input
5 1 5
1 1 1 1 1
3 1 5 4 2
Output
3 1 5 4 2
Input
4 2 9
3 4 8 9
3 2 1 4
Output
2 2 2 9
Input
6 1 5
1 1 1 1 1 1
2 3 5 4 1 6
Output
-1
Note
Sequence b which was found in the second sample is suitable, because calculated sequence c = [2 - 3, 2 - 4, 2 - 8, 9 - 9] = [ - 1, - 2, - 6, 0] (note that ci = bi - ai) has compressed sequence equals to p = [3, 2, 1, 4].
Tags: binary search, brute force, constructive algorithms, greedy, sortings
Correct Solution:
```
n, l, r = list(map(int, input().split()))
a = list(map(int, input().split()))
p = list(map(int, input().split()))
s = set()
x = []
for i in range(len(a)):
x.append([p[i], i])
x.sort()
mx = -1000000000000
for i in range(n):
p[x[i][1]] = max(l, mx + a[x[i][1]] + 1)
if p[x[i][1]] > r:
print('-1')
exit(0)
mx = p[x[i][1]] - a[x[i][1]]
idx = 0
for i in p:
if idx != 0:
print("", i, end="")
else:
print(i, end="")
idx = 1
print('')
```
| 84,686 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Dasha logged into the system and began to solve problems. One of them is as follows:
Given two sequences a and b of length n each you need to write a sequence c of length n, the i-th element of which is calculated as follows: ci = bi - ai.
About sequences a and b we know that their elements are in the range from l to r. More formally, elements satisfy the following conditions: l β€ ai β€ r and l β€ bi β€ r. About sequence c we know that all its elements are distinct.
<image>
Dasha wrote a solution to that problem quickly, but checking her work on the standard test was not so easy. Due to an error in the test system only the sequence a and the compressed sequence of the sequence c were known from that test.
Let's give the definition to a compressed sequence. A compressed sequence of sequence c of length n is a sequence p of length n, so that pi equals to the number of integers which are less than or equal to ci in the sequence c. For example, for the sequence c = [250, 200, 300, 100, 50] the compressed sequence will be p = [4, 3, 5, 2, 1]. Pay attention that in c all integers are distinct. Consequently, the compressed sequence contains all integers from 1 to n inclusively.
Help Dasha to find any sequence b for which the calculated compressed sequence of sequence c is correct.
Input
The first line contains three integers n, l, r (1 β€ n β€ 105, 1 β€ l β€ r β€ 109) β the length of the sequence and boundaries of the segment where the elements of sequences a and b are.
The next line contains n integers a1, a2, ..., an (l β€ ai β€ r) β the elements of the sequence a.
The next line contains n distinct integers p1, p2, ..., pn (1 β€ pi β€ n) β the compressed sequence of the sequence c.
Output
If there is no the suitable sequence b, then in the only line print "-1".
Otherwise, in the only line print n integers β the elements of any suitable sequence b.
Examples
Input
5 1 5
1 1 1 1 1
3 1 5 4 2
Output
3 1 5 4 2
Input
4 2 9
3 4 8 9
3 2 1 4
Output
2 2 2 9
Input
6 1 5
1 1 1 1 1 1
2 3 5 4 1 6
Output
-1
Note
Sequence b which was found in the second sample is suitable, because calculated sequence c = [2 - 3, 2 - 4, 2 - 8, 9 - 9] = [ - 1, - 2, - 6, 0] (note that ci = bi - ai) has compressed sequence equals to p = [3, 2, 1, 4].
Submitted Solution:
```
#!/usr/bin/env python3
from sys import stdin,stdout
def ri():
return map(int, input().split())
n, l, r = ri()
a = list(ri())
p = list(ri())
pi = [i for i in range(n)]
pi.sort(key=lambda e: p[e])
b = [0 for i in range(n)]
i = pi[0]
b[i] = l
cp = b[i] - a[i]
for ii in range(1,n):
i = pi[ii]
if a[i] + cp + 1 >=l:
b[i] = a[i] + cp + 1
else:
b[i] = l
cp = b[i] - a[i]
if b[i] > r:
print(-1)
exit()
print(*b)
```
Yes
| 84,687 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Dasha logged into the system and began to solve problems. One of them is as follows:
Given two sequences a and b of length n each you need to write a sequence c of length n, the i-th element of which is calculated as follows: ci = bi - ai.
About sequences a and b we know that their elements are in the range from l to r. More formally, elements satisfy the following conditions: l β€ ai β€ r and l β€ bi β€ r. About sequence c we know that all its elements are distinct.
<image>
Dasha wrote a solution to that problem quickly, but checking her work on the standard test was not so easy. Due to an error in the test system only the sequence a and the compressed sequence of the sequence c were known from that test.
Let's give the definition to a compressed sequence. A compressed sequence of sequence c of length n is a sequence p of length n, so that pi equals to the number of integers which are less than or equal to ci in the sequence c. For example, for the sequence c = [250, 200, 300, 100, 50] the compressed sequence will be p = [4, 3, 5, 2, 1]. Pay attention that in c all integers are distinct. Consequently, the compressed sequence contains all integers from 1 to n inclusively.
Help Dasha to find any sequence b for which the calculated compressed sequence of sequence c is correct.
Input
The first line contains three integers n, l, r (1 β€ n β€ 105, 1 β€ l β€ r β€ 109) β the length of the sequence and boundaries of the segment where the elements of sequences a and b are.
The next line contains n integers a1, a2, ..., an (l β€ ai β€ r) β the elements of the sequence a.
The next line contains n distinct integers p1, p2, ..., pn (1 β€ pi β€ n) β the compressed sequence of the sequence c.
Output
If there is no the suitable sequence b, then in the only line print "-1".
Otherwise, in the only line print n integers β the elements of any suitable sequence b.
Examples
Input
5 1 5
1 1 1 1 1
3 1 5 4 2
Output
3 1 5 4 2
Input
4 2 9
3 4 8 9
3 2 1 4
Output
2 2 2 9
Input
6 1 5
1 1 1 1 1 1
2 3 5 4 1 6
Output
-1
Note
Sequence b which was found in the second sample is suitable, because calculated sequence c = [2 - 3, 2 - 4, 2 - 8, 9 - 9] = [ - 1, - 2, - 6, 0] (note that ci = bi - ai) has compressed sequence equals to p = [3, 2, 1, 4].
Submitted Solution:
```
#Code by Sounak, IIESTS
#------------------------------warmup----------------------------
import os
import sys
import math
from io import BytesIO, IOBase
from fractions import Fraction
import collections
from itertools import permutations
from collections import defaultdict
from collections import deque
import threading
threading.stack_size(10**8)
sys.setrecursionlimit(300000)
BUFSIZE = 8192
class FastIO(IOBase):
newlines = 0
def __init__(self, file):
self._fd = file.fileno()
self.buffer = BytesIO()
self.writable = "x" in file.mode or "r" not in file.mode
self.write = self.buffer.write if self.writable else None
def read(self):
while True:
b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
if not b:
break
ptr = self.buffer.tell()
self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr)
self.newlines = 0
return self.buffer.read()
def readline(self):
while self.newlines == 0:
b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
self.newlines = b.count(b"\n") + (not b)
ptr = self.buffer.tell()
self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr)
self.newlines -= 1
return self.buffer.readline()
def flush(self):
if self.writable:
os.write(self._fd, self.buffer.getvalue())
self.buffer.truncate(0), self.buffer.seek(0)
class IOWrapper(IOBase):
def __init__(self, file):
self.buffer = FastIO(file)
self.flush = self.buffer.flush
self.writable = self.buffer.writable
self.write = lambda s: self.buffer.write(s.encode("ascii"))
self.read = lambda: self.buffer.read().decode("ascii")
self.readline = lambda: self.buffer.readline().decode("ascii")
sys.stdin, sys.stdout = IOWrapper(sys.stdin), IOWrapper(sys.stdout)
input = lambda: sys.stdin.readline().rstrip("\r\n")
#-------------------game starts now-----------------------------------------------------
class Factorial:
def __init__(self, MOD):
self.MOD = MOD
self.factorials = [1, 1]
self.invModulos = [0, 1]
self.invFactorial_ = [1, 1]
def calc(self, n):
if n <= -1:
print("Invalid argument to calculate n!")
print("n must be non-negative value. But the argument was " + str(n))
exit()
if n < len(self.factorials):
return self.factorials[n]
nextArr = [0] * (n + 1 - len(self.factorials))
initialI = len(self.factorials)
prev = self.factorials[-1]
m = self.MOD
for i in range(initialI, n + 1):
prev = nextArr[i - initialI] = prev * i % m
self.factorials += nextArr
return self.factorials[n]
def inv(self, n):
if n <= -1:
print("Invalid argument to calculate n^(-1)")
print("n must be non-negative value. But the argument was " + str(n))
exit()
p = self.MOD
pi = n % p
if pi < len(self.invModulos):
return self.invModulos[pi]
nextArr = [0] * (n + 1 - len(self.invModulos))
initialI = len(self.invModulos)
for i in range(initialI, min(p, n + 1)):
next = -self.invModulos[p % i] * (p // i) % p
self.invModulos.append(next)
return self.invModulos[pi]
def invFactorial(self, n):
if n <= -1:
print("Invalid argument to calculate (n^(-1))!")
print("n must be non-negative value. But the argument was " + str(n))
exit()
if n < len(self.invFactorial_):
return self.invFactorial_[n]
self.inv(n) # To make sure already calculated n^-1
nextArr = [0] * (n + 1 - len(self.invFactorial_))
initialI = len(self.invFactorial_)
prev = self.invFactorial_[-1]
p = self.MOD
for i in range(initialI, n + 1):
prev = nextArr[i - initialI] = (prev * self.invModulos[i % p]) % p
self.invFactorial_ += nextArr
return self.invFactorial_[n]
class Combination:
def __init__(self, MOD):
self.MOD = MOD
self.factorial = Factorial(MOD)
def ncr(self, n, k):
if k < 0 or n < k:
return 0
k = min(k, n - k)
f = self.factorial
return f.calc(n) * f.invFactorial(max(n - k, k)) * f.invFactorial(min(k, n - k)) % self.MOD
#-------------------------------------------------------------------------
n,l,r=map(int,input().split())
a=list(map(int,input().split()))
p=list(map(int,input().split()))
el=0
b=[0]*n
for i in range (n):
b[i]=a[i]+p[i]
m=max(b)
m=max(0,m-r)
ch=1
for i in range (n):
b[i]-=m
if b[i]>r or b[i]<l:
ch=0
if ch:
print(*b)
else:
print(-1)
```
Yes
| 84,688 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Dasha logged into the system and began to solve problems. One of them is as follows:
Given two sequences a and b of length n each you need to write a sequence c of length n, the i-th element of which is calculated as follows: ci = bi - ai.
About sequences a and b we know that their elements are in the range from l to r. More formally, elements satisfy the following conditions: l β€ ai β€ r and l β€ bi β€ r. About sequence c we know that all its elements are distinct.
<image>
Dasha wrote a solution to that problem quickly, but checking her work on the standard test was not so easy. Due to an error in the test system only the sequence a and the compressed sequence of the sequence c were known from that test.
Let's give the definition to a compressed sequence. A compressed sequence of sequence c of length n is a sequence p of length n, so that pi equals to the number of integers which are less than or equal to ci in the sequence c. For example, for the sequence c = [250, 200, 300, 100, 50] the compressed sequence will be p = [4, 3, 5, 2, 1]. Pay attention that in c all integers are distinct. Consequently, the compressed sequence contains all integers from 1 to n inclusively.
Help Dasha to find any sequence b for which the calculated compressed sequence of sequence c is correct.
Input
The first line contains three integers n, l, r (1 β€ n β€ 105, 1 β€ l β€ r β€ 109) β the length of the sequence and boundaries of the segment where the elements of sequences a and b are.
The next line contains n integers a1, a2, ..., an (l β€ ai β€ r) β the elements of the sequence a.
The next line contains n distinct integers p1, p2, ..., pn (1 β€ pi β€ n) β the compressed sequence of the sequence c.
Output
If there is no the suitable sequence b, then in the only line print "-1".
Otherwise, in the only line print n integers β the elements of any suitable sequence b.
Examples
Input
5 1 5
1 1 1 1 1
3 1 5 4 2
Output
3 1 5 4 2
Input
4 2 9
3 4 8 9
3 2 1 4
Output
2 2 2 9
Input
6 1 5
1 1 1 1 1 1
2 3 5 4 1 6
Output
-1
Note
Sequence b which was found in the second sample is suitable, because calculated sequence c = [2 - 3, 2 - 4, 2 - 8, 9 - 9] = [ - 1, - 2, - 6, 0] (note that ci = bi - ai) has compressed sequence equals to p = [3, 2, 1, 4].
Submitted Solution:
```
n, l, r = [int(el) for el in input().split()]
a = [int(el) for el in input().split()]
p = [int(el) for el in input().split()]
b = [a[i] + p[i] for i in range(n)]
mx = max(b)
mn = min(b)
if mx <= r:
print(' '.join([str(el) for el in b]))
else:
diff = mx - r
if mn - diff >= l:
print(' '.join([str(el - diff) for el in b]))
else:
print(-1)
```
Yes
| 84,689 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Dasha logged into the system and began to solve problems. One of them is as follows:
Given two sequences a and b of length n each you need to write a sequence c of length n, the i-th element of which is calculated as follows: ci = bi - ai.
About sequences a and b we know that their elements are in the range from l to r. More formally, elements satisfy the following conditions: l β€ ai β€ r and l β€ bi β€ r. About sequence c we know that all its elements are distinct.
<image>
Dasha wrote a solution to that problem quickly, but checking her work on the standard test was not so easy. Due to an error in the test system only the sequence a and the compressed sequence of the sequence c were known from that test.
Let's give the definition to a compressed sequence. A compressed sequence of sequence c of length n is a sequence p of length n, so that pi equals to the number of integers which are less than or equal to ci in the sequence c. For example, for the sequence c = [250, 200, 300, 100, 50] the compressed sequence will be p = [4, 3, 5, 2, 1]. Pay attention that in c all integers are distinct. Consequently, the compressed sequence contains all integers from 1 to n inclusively.
Help Dasha to find any sequence b for which the calculated compressed sequence of sequence c is correct.
Input
The first line contains three integers n, l, r (1 β€ n β€ 105, 1 β€ l β€ r β€ 109) β the length of the sequence and boundaries of the segment where the elements of sequences a and b are.
The next line contains n integers a1, a2, ..., an (l β€ ai β€ r) β the elements of the sequence a.
The next line contains n distinct integers p1, p2, ..., pn (1 β€ pi β€ n) β the compressed sequence of the sequence c.
Output
If there is no the suitable sequence b, then in the only line print "-1".
Otherwise, in the only line print n integers β the elements of any suitable sequence b.
Examples
Input
5 1 5
1 1 1 1 1
3 1 5 4 2
Output
3 1 5 4 2
Input
4 2 9
3 4 8 9
3 2 1 4
Output
2 2 2 9
Input
6 1 5
1 1 1 1 1 1
2 3 5 4 1 6
Output
-1
Note
Sequence b which was found in the second sample is suitable, because calculated sequence c = [2 - 3, 2 - 4, 2 - 8, 9 - 9] = [ - 1, - 2, - 6, 0] (note that ci = bi - ai) has compressed sequence equals to p = [3, 2, 1, 4].
Submitted Solution:
```
n, l, r = map(int,input().split(" "))
a = list(map(int, input().split(" ")))
compressed = list(map(int, input().split(" ")))
#print('n,l,r')
#print(n,l,r)
b = [0]*n
lastmod = -1
lol = list(zip(compressed, enumerate(a)))
#print('sorted lol')
#print(sorted(lol))
for i, (pos, val) in sorted(lol):
# print('position of a, val of a in that pos')
# print(pos, val)
# print('lastmod')
# print(lastmod)
if i == 1:
b[pos] = l
lastmod = pos
if i > 1:
b[pos] = max(b[lastmod] - a[lastmod] + val + 1, l)
if b[pos] > r:
print("-1")
exit()
lastmod = pos
# print('b is now')
# print(b)
for i in b:
print(i, end=" ")
```
Yes
| 84,690 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Dasha logged into the system and began to solve problems. One of them is as follows:
Given two sequences a and b of length n each you need to write a sequence c of length n, the i-th element of which is calculated as follows: ci = bi - ai.
About sequences a and b we know that their elements are in the range from l to r. More formally, elements satisfy the following conditions: l β€ ai β€ r and l β€ bi β€ r. About sequence c we know that all its elements are distinct.
<image>
Dasha wrote a solution to that problem quickly, but checking her work on the standard test was not so easy. Due to an error in the test system only the sequence a and the compressed sequence of the sequence c were known from that test.
Let's give the definition to a compressed sequence. A compressed sequence of sequence c of length n is a sequence p of length n, so that pi equals to the number of integers which are less than or equal to ci in the sequence c. For example, for the sequence c = [250, 200, 300, 100, 50] the compressed sequence will be p = [4, 3, 5, 2, 1]. Pay attention that in c all integers are distinct. Consequently, the compressed sequence contains all integers from 1 to n inclusively.
Help Dasha to find any sequence b for which the calculated compressed sequence of sequence c is correct.
Input
The first line contains three integers n, l, r (1 β€ n β€ 105, 1 β€ l β€ r β€ 109) β the length of the sequence and boundaries of the segment where the elements of sequences a and b are.
The next line contains n integers a1, a2, ..., an (l β€ ai β€ r) β the elements of the sequence a.
The next line contains n distinct integers p1, p2, ..., pn (1 β€ pi β€ n) β the compressed sequence of the sequence c.
Output
If there is no the suitable sequence b, then in the only line print "-1".
Otherwise, in the only line print n integers β the elements of any suitable sequence b.
Examples
Input
5 1 5
1 1 1 1 1
3 1 5 4 2
Output
3 1 5 4 2
Input
4 2 9
3 4 8 9
3 2 1 4
Output
2 2 2 9
Input
6 1 5
1 1 1 1 1 1
2 3 5 4 1 6
Output
-1
Note
Sequence b which was found in the second sample is suitable, because calculated sequence c = [2 - 3, 2 - 4, 2 - 8, 9 - 9] = [ - 1, - 2, - 6, 0] (note that ci = bi - ai) has compressed sequence equals to p = [3, 2, 1, 4].
Submitted Solution:
```
n,l,r = map(int,input().split())
a = list(map(int,input().split()))
p = list(map(int,input().split()))
b = [0]*n
c = [0]*n
seq = [(x,i) for i,x in enumerate(p)]
seq.sort()
diff = 0
for x in seq:
i = x[1]
c[i] = diff
b[i]= a[i] + diff
if b[i] < l or b[i] > r:
b[i] = a[i] - diff
if b[i] < l or b[i] > r:
print(-1)
exit()
diff += 1
for x in b:
print(x,end=' ')
print()
```
No
| 84,691 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Dasha logged into the system and began to solve problems. One of them is as follows:
Given two sequences a and b of length n each you need to write a sequence c of length n, the i-th element of which is calculated as follows: ci = bi - ai.
About sequences a and b we know that their elements are in the range from l to r. More formally, elements satisfy the following conditions: l β€ ai β€ r and l β€ bi β€ r. About sequence c we know that all its elements are distinct.
<image>
Dasha wrote a solution to that problem quickly, but checking her work on the standard test was not so easy. Due to an error in the test system only the sequence a and the compressed sequence of the sequence c were known from that test.
Let's give the definition to a compressed sequence. A compressed sequence of sequence c of length n is a sequence p of length n, so that pi equals to the number of integers which are less than or equal to ci in the sequence c. For example, for the sequence c = [250, 200, 300, 100, 50] the compressed sequence will be p = [4, 3, 5, 2, 1]. Pay attention that in c all integers are distinct. Consequently, the compressed sequence contains all integers from 1 to n inclusively.
Help Dasha to find any sequence b for which the calculated compressed sequence of sequence c is correct.
Input
The first line contains three integers n, l, r (1 β€ n β€ 105, 1 β€ l β€ r β€ 109) β the length of the sequence and boundaries of the segment where the elements of sequences a and b are.
The next line contains n integers a1, a2, ..., an (l β€ ai β€ r) β the elements of the sequence a.
The next line contains n distinct integers p1, p2, ..., pn (1 β€ pi β€ n) β the compressed sequence of the sequence c.
Output
If there is no the suitable sequence b, then in the only line print "-1".
Otherwise, in the only line print n integers β the elements of any suitable sequence b.
Examples
Input
5 1 5
1 1 1 1 1
3 1 5 4 2
Output
3 1 5 4 2
Input
4 2 9
3 4 8 9
3 2 1 4
Output
2 2 2 9
Input
6 1 5
1 1 1 1 1 1
2 3 5 4 1 6
Output
-1
Note
Sequence b which was found in the second sample is suitable, because calculated sequence c = [2 - 3, 2 - 4, 2 - 8, 9 - 9] = [ - 1, - 2, - 6, 0] (note that ci = bi - ai) has compressed sequence equals to p = [3, 2, 1, 4].
Submitted Solution:
```
n, l, r = [int(i) for i in input().split()]
a = [int(i) for i in input().split()]
p = [int(i) for i in input().split()]
pos = []
b = [0] * n
for i in range(n):
pos.append((p[i], i))
pos.sort()
b[pos[0][1]] = l
c = [0] * n
c[pos[0][1]] = l - a[pos[0][1]]
cur = c[pos[0][1]]
for i in range(1, n):
b[pos[i][1]] = cur + 1 + a[pos[i][1]]
cur += 1
m = min(b)
if max(b) > r:
print(-1)
exit()
print(*b)
```
No
| 84,692 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Dasha logged into the system and began to solve problems. One of them is as follows:
Given two sequences a and b of length n each you need to write a sequence c of length n, the i-th element of which is calculated as follows: ci = bi - ai.
About sequences a and b we know that their elements are in the range from l to r. More formally, elements satisfy the following conditions: l β€ ai β€ r and l β€ bi β€ r. About sequence c we know that all its elements are distinct.
<image>
Dasha wrote a solution to that problem quickly, but checking her work on the standard test was not so easy. Due to an error in the test system only the sequence a and the compressed sequence of the sequence c were known from that test.
Let's give the definition to a compressed sequence. A compressed sequence of sequence c of length n is a sequence p of length n, so that pi equals to the number of integers which are less than or equal to ci in the sequence c. For example, for the sequence c = [250, 200, 300, 100, 50] the compressed sequence will be p = [4, 3, 5, 2, 1]. Pay attention that in c all integers are distinct. Consequently, the compressed sequence contains all integers from 1 to n inclusively.
Help Dasha to find any sequence b for which the calculated compressed sequence of sequence c is correct.
Input
The first line contains three integers n, l, r (1 β€ n β€ 105, 1 β€ l β€ r β€ 109) β the length of the sequence and boundaries of the segment where the elements of sequences a and b are.
The next line contains n integers a1, a2, ..., an (l β€ ai β€ r) β the elements of the sequence a.
The next line contains n distinct integers p1, p2, ..., pn (1 β€ pi β€ n) β the compressed sequence of the sequence c.
Output
If there is no the suitable sequence b, then in the only line print "-1".
Otherwise, in the only line print n integers β the elements of any suitable sequence b.
Examples
Input
5 1 5
1 1 1 1 1
3 1 5 4 2
Output
3 1 5 4 2
Input
4 2 9
3 4 8 9
3 2 1 4
Output
2 2 2 9
Input
6 1 5
1 1 1 1 1 1
2 3 5 4 1 6
Output
-1
Note
Sequence b which was found in the second sample is suitable, because calculated sequence c = [2 - 3, 2 - 4, 2 - 8, 9 - 9] = [ - 1, - 2, - 6, 0] (note that ci = bi - ai) has compressed sequence equals to p = [3, 2, 1, 4].
Submitted Solution:
```
def binary_search(l, r, k):
while (l <= r):
mid = l+r >> 1
if (mid < k):
l = mid+1
else:
r = mid-1
return l
def main():
n, l, r = map(int, input().split())
a = list(map(int, input().split()))
p = list(map(int, input().split()))
p = [(p[i], i+1) for i in range(n)]
a.sort()
p.sort()
b = [0]*(n+1)
b[p[0][1] - 1] = l
for i in range(1,n):
idx_list = p[i-1][1] - 1
b[p[i][1]-1] = binary_search(l, r, b[idx_list] - a[i-1] + a[i])
if (b[idx_list] - a[i-1] == b[p[i][1]-1] - a[i]):
b[p[i][1]-1] += 1
if (b[p[i][1] - 1] > r):
print(-1)
return
for i in range(n):
print(b[i], end=' ')
main()
```
No
| 84,693 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Dasha logged into the system and began to solve problems. One of them is as follows:
Given two sequences a and b of length n each you need to write a sequence c of length n, the i-th element of which is calculated as follows: ci = bi - ai.
About sequences a and b we know that their elements are in the range from l to r. More formally, elements satisfy the following conditions: l β€ ai β€ r and l β€ bi β€ r. About sequence c we know that all its elements are distinct.
<image>
Dasha wrote a solution to that problem quickly, but checking her work on the standard test was not so easy. Due to an error in the test system only the sequence a and the compressed sequence of the sequence c were known from that test.
Let's give the definition to a compressed sequence. A compressed sequence of sequence c of length n is a sequence p of length n, so that pi equals to the number of integers which are less than or equal to ci in the sequence c. For example, for the sequence c = [250, 200, 300, 100, 50] the compressed sequence will be p = [4, 3, 5, 2, 1]. Pay attention that in c all integers are distinct. Consequently, the compressed sequence contains all integers from 1 to n inclusively.
Help Dasha to find any sequence b for which the calculated compressed sequence of sequence c is correct.
Input
The first line contains three integers n, l, r (1 β€ n β€ 105, 1 β€ l β€ r β€ 109) β the length of the sequence and boundaries of the segment where the elements of sequences a and b are.
The next line contains n integers a1, a2, ..., an (l β€ ai β€ r) β the elements of the sequence a.
The next line contains n distinct integers p1, p2, ..., pn (1 β€ pi β€ n) β the compressed sequence of the sequence c.
Output
If there is no the suitable sequence b, then in the only line print "-1".
Otherwise, in the only line print n integers β the elements of any suitable sequence b.
Examples
Input
5 1 5
1 1 1 1 1
3 1 5 4 2
Output
3 1 5 4 2
Input
4 2 9
3 4 8 9
3 2 1 4
Output
2 2 2 9
Input
6 1 5
1 1 1 1 1 1
2 3 5 4 1 6
Output
-1
Note
Sequence b which was found in the second sample is suitable, because calculated sequence c = [2 - 3, 2 - 4, 2 - 8, 9 - 9] = [ - 1, - 2, - 6, 0] (note that ci = bi - ai) has compressed sequence equals to p = [3, 2, 1, 4].
Submitted Solution:
```
read = lambda: map(int, input().split())
```
No
| 84,694 |
Provide tags and a correct Python 3 solution for this coding contest problem.
You are developing a new feature for the website which sells airline tickets: being able to sort tickets by price! You have already extracted the tickets' prices, so there's just the last step to be done...
You are given an array of integers. Sort it in non-descending order.
Input
The input consists of a single line of space-separated integers. The first number is n (1 β€ n β€ 10) β the size of the array. The following n numbers are the elements of the array (1 β€ ai β€ 100).
Output
Output space-separated elements of the sorted array.
Example
Input
3 3 1 2
Output
1 2 3
Note
Remember, this is a very important feature, and you have to make sure the customers appreciate it!
Tags: *special, implementation
Correct Solution:
```
a=123**511211
print(*sorted(list(map(int,input().split()))[1:]))
```
| 84,695 |
Provide tags and a correct Python 3 solution for this coding contest problem.
You are developing a new feature for the website which sells airline tickets: being able to sort tickets by price! You have already extracted the tickets' prices, so there's just the last step to be done...
You are given an array of integers. Sort it in non-descending order.
Input
The input consists of a single line of space-separated integers. The first number is n (1 β€ n β€ 10) β the size of the array. The following n numbers are the elements of the array (1 β€ ai β€ 100).
Output
Output space-separated elements of the sorted array.
Example
Input
3 3 1 2
Output
1 2 3
Note
Remember, this is a very important feature, and you have to make sure the customers appreciate it!
Tags: *special, implementation
Correct Solution:
```
import time
a=input().split()
n=int(a[0])
del(a[0])
a=map(int,a)
a=sorted(a)
b=[10,30,10,30,10,30,10,30,10,30,10,30,10,30,10,30,10,30,10,30,10,30,10,30,10,30,10,30,10,30,10,30,10,30,10,30,10,30,10,30,10,30,10,30,10,30,10,30,10,30,10,30,10,30,10,30]
for i in range(2500000):
b=b*i
sorted(b)
for i in range(len(a)):
print(a[i],end=" ")
```
| 84,696 |
Provide tags and a correct Python 3 solution for this coding contest problem.
You are developing a new feature for the website which sells airline tickets: being able to sort tickets by price! You have already extracted the tickets' prices, so there's just the last step to be done...
You are given an array of integers. Sort it in non-descending order.
Input
The input consists of a single line of space-separated integers. The first number is n (1 β€ n β€ 10) β the size of the array. The following n numbers are the elements of the array (1 β€ ai β€ 100).
Output
Output space-separated elements of the sorted array.
Example
Input
3 3 1 2
Output
1 2 3
Note
Remember, this is a very important feature, and you have to make sure the customers appreciate it!
Tags: *special, implementation
Correct Solution:
```
cnt=1234**456789
print(*sorted([*map(int,input().split())][1:]))
```
| 84,697 |
Provide tags and a correct Python 3 solution for this coding contest problem.
You are developing a new feature for the website which sells airline tickets: being able to sort tickets by price! You have already extracted the tickets' prices, so there's just the last step to be done...
You are given an array of integers. Sort it in non-descending order.
Input
The input consists of a single line of space-separated integers. The first number is n (1 β€ n β€ 10) β the size of the array. The following n numbers are the elements of the array (1 β€ ai β€ 100).
Output
Output space-separated elements of the sorted array.
Example
Input
3 3 1 2
Output
1 2 3
Note
Remember, this is a very important feature, and you have to make sure the customers appreciate it!
Tags: *special, implementation
Correct Solution:
```
# coding: utf-8
from time import time
initial = time()
while time() - initial < 1:
continue
a = sorted(list(map(int, input().split()))[1:])
print(*a, sep = ' ')
```
| 84,698 |
Provide tags and a correct Python 3 solution for this coding contest problem.
You are developing a new feature for the website which sells airline tickets: being able to sort tickets by price! You have already extracted the tickets' prices, so there's just the last step to be done...
You are given an array of integers. Sort it in non-descending order.
Input
The input consists of a single line of space-separated integers. The first number is n (1 β€ n β€ 10) β the size of the array. The following n numbers are the elements of the array (1 β€ ai β€ 100).
Output
Output space-separated elements of the sorted array.
Example
Input
3 3 1 2
Output
1 2 3
Note
Remember, this is a very important feature, and you have to make sure the customers appreciate it!
Tags: *special, implementation
Correct Solution:
```
import time
kal = list(map(int,input().split()))
p = kal[1:]
kaleee = []
for i in range(6300):
kaleee.append(i)
kaleee.count(i)
p.sort()
for i in p:
print(i,end=' ')
```
| 84,699 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.