text stringlengths 198 433k | conversation_id int64 0 109k |
|---|---|
Provide tags and a correct Python 3 solution for this coding contest problem.
For years, the Day of city N was held in the most rainy day of summer. New mayor decided to break this tradition and select a not-so-rainy day for the celebration. The mayor knows the weather forecast for the n days of summer. On the i-th day, a_i millimeters of rain will fall. All values a_i are distinct.
The mayor knows that citizens will watch the weather x days before the celebration and y days after. Because of that, he says that a day d is not-so-rainy if a_d is smaller than rain amounts at each of x days before day d and and each of y days after day d. In other words, a_d < a_j should hold for all d - x ≤ j < d and d < j ≤ d + y. Citizens only watch the weather during summer, so we only consider such j that 1 ≤ j ≤ n.
Help mayor find the earliest not-so-rainy day of summer.
Input
The first line contains three integers n, x and y (1 ≤ n ≤ 100 000, 0 ≤ x, y ≤ 7) — the number of days in summer, the number of days citizens watch the weather before the celebration and the number of days they do that after.
The second line contains n distinct integers a_1, a_2, ..., a_n (1 ≤ a_i ≤ 10^9), where a_i denotes the rain amount on the i-th day.
Output
Print a single integer — the index of the earliest not-so-rainy day of summer. We can show that the answer always exists.
Examples
Input
10 2 2
10 9 6 7 8 3 2 1 4 5
Output
3
Input
10 2 3
10 9 6 7 8 3 2 1 4 5
Output
8
Input
5 5 5
100000 10000 1000 100 10
Output
5
Note
In the first example days 3 and 8 are not-so-rainy. The 3-rd day is earlier.
In the second example day 3 is not not-so-rainy, because 3 + y = 6 and a_3 > a_6. Thus, day 8 is the answer. Note that 8 + y = 11, but we don't consider day 11, because it is not summer.
Tags: implementation
Correct Solution:
```
n,x,y=map(int,input().split(" "))
a=list(map(int,input().split()))
i=f1=0
while i<n:
if i-x<0:
start=0
else:
start=i-x
if i+y>n-1:
end=n-1
else:
end=i+y
f=0
j=start
while j<=end:
if i!=j:
if a[i]<a[j]:
j+=1
else:
f=1
break
else:
j+=1
if f==0:
f1=1
break
i+=1
if f1==1:
print(i+1)
```
| 98,700 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
For years, the Day of city N was held in the most rainy day of summer. New mayor decided to break this tradition and select a not-so-rainy day for the celebration. The mayor knows the weather forecast for the n days of summer. On the i-th day, a_i millimeters of rain will fall. All values a_i are distinct.
The mayor knows that citizens will watch the weather x days before the celebration and y days after. Because of that, he says that a day d is not-so-rainy if a_d is smaller than rain amounts at each of x days before day d and and each of y days after day d. In other words, a_d < a_j should hold for all d - x ≤ j < d and d < j ≤ d + y. Citizens only watch the weather during summer, so we only consider such j that 1 ≤ j ≤ n.
Help mayor find the earliest not-so-rainy day of summer.
Input
The first line contains three integers n, x and y (1 ≤ n ≤ 100 000, 0 ≤ x, y ≤ 7) — the number of days in summer, the number of days citizens watch the weather before the celebration and the number of days they do that after.
The second line contains n distinct integers a_1, a_2, ..., a_n (1 ≤ a_i ≤ 10^9), where a_i denotes the rain amount on the i-th day.
Output
Print a single integer — the index of the earliest not-so-rainy day of summer. We can show that the answer always exists.
Examples
Input
10 2 2
10 9 6 7 8 3 2 1 4 5
Output
3
Input
10 2 3
10 9 6 7 8 3 2 1 4 5
Output
8
Input
5 5 5
100000 10000 1000 100 10
Output
5
Note
In the first example days 3 and 8 are not-so-rainy. The 3-rd day is earlier.
In the second example day 3 is not not-so-rainy, because 3 + y = 6 and a_3 > a_6. Thus, day 8 is the answer. Note that 8 + y = 11, but we don't consider day 11, because it is not summer.
Submitted Solution:
```
from collections import defaultdict, deque, Counter
from sys import stdin, stdout
from heapq import heappush, heappop
import math
import io
import os
import math
import bisect
#?############################################################
def isPrime(x):
for i in range(2, x):
if i*i > x:
break
if (x % i == 0):
return False
return True
#?############################################################
def ncr(n, r, p):
num = den = 1
for i in range(r):
num = (num * (n - i)) % p
den = (den * (i + 1)) % p
return (num * pow(den, p - 2, p)) % p
#?############################################################
def primeFactors(n):
l = []
while n % 2 == 0:
l.append(2)
n = n / 2
for i in range(3, int(math.sqrt(n))+1, 2):
while n % i == 0:
l.append(int(i))
n = n / i
if n > 2:
l.append(n)
return list(set(l))
#?############################################################
def power(x, y, p):
res = 1
x = x % p
if (x == 0):
return 0
while (y > 0):
if ((y & 1) == 1):
res = (res * x) % p
y = y >> 1
x = (x * x) % p
return res
#?############################################################
def sieve(n):
prime = [True for i in range(n+1)]
p = 2
while (p * p <= n):
if (prime[p] == True):
for i in range(p * p, n+1, p):
prime[i] = False
p += 1
return prime
#?############################################################
def digits(n):
c = 0
while (n > 0):
n //= 10
c += 1
return c
#?############################################################
def ceil(n, x):
if (n % x == 0):
return n//x
return n//x+1
#?############################################################
def mapin():
return map(int, input().split())
#?############################################################
input = io.BytesIO(os.read(0, os.fstat(0).st_size)).readline
# python3 15.py<in>op
n, x, y = mapin()
fl = 0
a = [int(x) for x in input().split()]
for i in range(n):
s = min(a[max(0,i-x):min(n,i+y+1)])
if(a[i] == s):
fl = i
break
print(fl+1)
```
Yes
| 98,701 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
For years, the Day of city N was held in the most rainy day of summer. New mayor decided to break this tradition and select a not-so-rainy day for the celebration. The mayor knows the weather forecast for the n days of summer. On the i-th day, a_i millimeters of rain will fall. All values a_i are distinct.
The mayor knows that citizens will watch the weather x days before the celebration and y days after. Because of that, he says that a day d is not-so-rainy if a_d is smaller than rain amounts at each of x days before day d and and each of y days after day d. In other words, a_d < a_j should hold for all d - x ≤ j < d and d < j ≤ d + y. Citizens only watch the weather during summer, so we only consider such j that 1 ≤ j ≤ n.
Help mayor find the earliest not-so-rainy day of summer.
Input
The first line contains three integers n, x and y (1 ≤ n ≤ 100 000, 0 ≤ x, y ≤ 7) — the number of days in summer, the number of days citizens watch the weather before the celebration and the number of days they do that after.
The second line contains n distinct integers a_1, a_2, ..., a_n (1 ≤ a_i ≤ 10^9), where a_i denotes the rain amount on the i-th day.
Output
Print a single integer — the index of the earliest not-so-rainy day of summer. We can show that the answer always exists.
Examples
Input
10 2 2
10 9 6 7 8 3 2 1 4 5
Output
3
Input
10 2 3
10 9 6 7 8 3 2 1 4 5
Output
8
Input
5 5 5
100000 10000 1000 100 10
Output
5
Note
In the first example days 3 and 8 are not-so-rainy. The 3-rd day is earlier.
In the second example day 3 is not not-so-rainy, because 3 + y = 6 and a_3 > a_6. Thus, day 8 is the answer. Note that 8 + y = 11, but we don't consider day 11, because it is not summer.
Submitted Solution:
```
n,x,y=map(int,input().split())
arr=list(map(int,input().split()))
for i in range(n):
ol=all(t>arr[i] for t in arr[i+1:min(i+y+1,n)])
uf=all(t>arr[i] for t in arr[max(i-x,0):i])
if ol==True and uf==True:
print(i+1)
break
```
Yes
| 98,702 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
For years, the Day of city N was held in the most rainy day of summer. New mayor decided to break this tradition and select a not-so-rainy day for the celebration. The mayor knows the weather forecast for the n days of summer. On the i-th day, a_i millimeters of rain will fall. All values a_i are distinct.
The mayor knows that citizens will watch the weather x days before the celebration and y days after. Because of that, he says that a day d is not-so-rainy if a_d is smaller than rain amounts at each of x days before day d and and each of y days after day d. In other words, a_d < a_j should hold for all d - x ≤ j < d and d < j ≤ d + y. Citizens only watch the weather during summer, so we only consider such j that 1 ≤ j ≤ n.
Help mayor find the earliest not-so-rainy day of summer.
Input
The first line contains three integers n, x and y (1 ≤ n ≤ 100 000, 0 ≤ x, y ≤ 7) — the number of days in summer, the number of days citizens watch the weather before the celebration and the number of days they do that after.
The second line contains n distinct integers a_1, a_2, ..., a_n (1 ≤ a_i ≤ 10^9), where a_i denotes the rain amount on the i-th day.
Output
Print a single integer — the index of the earliest not-so-rainy day of summer. We can show that the answer always exists.
Examples
Input
10 2 2
10 9 6 7 8 3 2 1 4 5
Output
3
Input
10 2 3
10 9 6 7 8 3 2 1 4 5
Output
8
Input
5 5 5
100000 10000 1000 100 10
Output
5
Note
In the first example days 3 and 8 are not-so-rainy. The 3-rd day is earlier.
In the second example day 3 is not not-so-rainy, because 3 + y = 6 and a_3 > a_6. Thus, day 8 is the answer. Note that 8 + y = 11, but we don't consider day 11, because it is not summer.
Submitted Solution:
```
from collections import deque
dq = deque()
n, x, y = map(int, input().split())
arr = list(map(int, input().split()))
for i in range(y):
while dq and arr[i] < arr[dq[-1]]:
dq.pop()
dq.append(i)
ans = -1
for i in range(y, n + y):
if i < n:
while dq and dq[0] < i - y - x:
dq.popleft()
while dq and arr[i] < arr[dq[-1]]:
dq.pop()
dq.append(i)
if dq[0] == i - y:
ans = dq[0] + 1
break
else:
while dq and dq[0] < i - y - x:
dq.popleft()
if dq[0] == i - y:
ans = dq[0] + 1
break
print(ans)
# h, l = 3, 5
# print((l ** 2 - h ** 2) / (2 * h))
```
Yes
| 98,703 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
For years, the Day of city N was held in the most rainy day of summer. New mayor decided to break this tradition and select a not-so-rainy day for the celebration. The mayor knows the weather forecast for the n days of summer. On the i-th day, a_i millimeters of rain will fall. All values a_i are distinct.
The mayor knows that citizens will watch the weather x days before the celebration and y days after. Because of that, he says that a day d is not-so-rainy if a_d is smaller than rain amounts at each of x days before day d and and each of y days after day d. In other words, a_d < a_j should hold for all d - x ≤ j < d and d < j ≤ d + y. Citizens only watch the weather during summer, so we only consider such j that 1 ≤ j ≤ n.
Help mayor find the earliest not-so-rainy day of summer.
Input
The first line contains three integers n, x and y (1 ≤ n ≤ 100 000, 0 ≤ x, y ≤ 7) — the number of days in summer, the number of days citizens watch the weather before the celebration and the number of days they do that after.
The second line contains n distinct integers a_1, a_2, ..., a_n (1 ≤ a_i ≤ 10^9), where a_i denotes the rain amount on the i-th day.
Output
Print a single integer — the index of the earliest not-so-rainy day of summer. We can show that the answer always exists.
Examples
Input
10 2 2
10 9 6 7 8 3 2 1 4 5
Output
3
Input
10 2 3
10 9 6 7 8 3 2 1 4 5
Output
8
Input
5 5 5
100000 10000 1000 100 10
Output
5
Note
In the first example days 3 and 8 are not-so-rainy. The 3-rd day is earlier.
In the second example day 3 is not not-so-rainy, because 3 + y = 6 and a_3 > a_6. Thus, day 8 is the answer. Note that 8 + y = 11, but we don't consider day 11, because it is not summer.
Submitted Solution:
```
a,b,c=map(int,input().split())
arr=list(map(int,input().split()))
for i in range(0,a):
flag=0
j=i+1
while(j<i+c+1 and j<a):
if(arr[i]>arr[j]):
flag=1
break
j+=1
if(flag==1):
continue
k=i-1
while(k>i-b-1 and k>=0):
if(arr[i]>arr[k]):
flag=1
break
k-=1
if(flag==0):
print(i+1)
break
```
Yes
| 98,704 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
For years, the Day of city N was held in the most rainy day of summer. New mayor decided to break this tradition and select a not-so-rainy day for the celebration. The mayor knows the weather forecast for the n days of summer. On the i-th day, a_i millimeters of rain will fall. All values a_i are distinct.
The mayor knows that citizens will watch the weather x days before the celebration and y days after. Because of that, he says that a day d is not-so-rainy if a_d is smaller than rain amounts at each of x days before day d and and each of y days after day d. In other words, a_d < a_j should hold for all d - x ≤ j < d and d < j ≤ d + y. Citizens only watch the weather during summer, so we only consider such j that 1 ≤ j ≤ n.
Help mayor find the earliest not-so-rainy day of summer.
Input
The first line contains three integers n, x and y (1 ≤ n ≤ 100 000, 0 ≤ x, y ≤ 7) — the number of days in summer, the number of days citizens watch the weather before the celebration and the number of days they do that after.
The second line contains n distinct integers a_1, a_2, ..., a_n (1 ≤ a_i ≤ 10^9), where a_i denotes the rain amount on the i-th day.
Output
Print a single integer — the index of the earliest not-so-rainy day of summer. We can show that the answer always exists.
Examples
Input
10 2 2
10 9 6 7 8 3 2 1 4 5
Output
3
Input
10 2 3
10 9 6 7 8 3 2 1 4 5
Output
8
Input
5 5 5
100000 10000 1000 100 10
Output
5
Note
In the first example days 3 and 8 are not-so-rainy. The 3-rd day is earlier.
In the second example day 3 is not not-so-rainy, because 3 + y = 6 and a_3 > a_6. Thus, day 8 is the answer. Note that 8 + y = 11, but we don't consider day 11, because it is not summer.
Submitted Solution:
```
n, x, y = map(int, input().split())
array = list(map(int, input().split()))
inf = float('inf')
ar_x = [float('inf')]*x
ar_y = []
for i in range(1, min(y+1, n)):
ar_y.append(array[i])
if not ar_y or array[0] == min(ar_y):
print(1)
exit(0)
for i in range(1, n):
ar_x.append(array[i-1])
if i + y < n:
ar_y.append(array[i+y])
ar_x.pop(0)
ar_y.pop(0)
if not ar_y and not ar_x:
print(i+1)
exit(0)
elif not ar_y and array[i] < min(ar_x):
print(i+1)
exit(0)
elif not ar_x and array[i] < min(ar_y):
print(i+1)
exit(0)
elif array[i] < min(ar_y) and array[i] < min(ar_x):
print(i+1)
exit(0)
```
No
| 98,705 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
For years, the Day of city N was held in the most rainy day of summer. New mayor decided to break this tradition and select a not-so-rainy day for the celebration. The mayor knows the weather forecast for the n days of summer. On the i-th day, a_i millimeters of rain will fall. All values a_i are distinct.
The mayor knows that citizens will watch the weather x days before the celebration and y days after. Because of that, he says that a day d is not-so-rainy if a_d is smaller than rain amounts at each of x days before day d and and each of y days after day d. In other words, a_d < a_j should hold for all d - x ≤ j < d and d < j ≤ d + y. Citizens only watch the weather during summer, so we only consider such j that 1 ≤ j ≤ n.
Help mayor find the earliest not-so-rainy day of summer.
Input
The first line contains three integers n, x and y (1 ≤ n ≤ 100 000, 0 ≤ x, y ≤ 7) — the number of days in summer, the number of days citizens watch the weather before the celebration and the number of days they do that after.
The second line contains n distinct integers a_1, a_2, ..., a_n (1 ≤ a_i ≤ 10^9), where a_i denotes the rain amount on the i-th day.
Output
Print a single integer — the index of the earliest not-so-rainy day of summer. We can show that the answer always exists.
Examples
Input
10 2 2
10 9 6 7 8 3 2 1 4 5
Output
3
Input
10 2 3
10 9 6 7 8 3 2 1 4 5
Output
8
Input
5 5 5
100000 10000 1000 100 10
Output
5
Note
In the first example days 3 and 8 are not-so-rainy. The 3-rd day is earlier.
In the second example day 3 is not not-so-rainy, because 3 + y = 6 and a_3 > a_6. Thus, day 8 is the answer. Note that 8 + y = 11, but we don't consider day 11, because it is not summer.
Submitted Solution:
```
n,x,y=list(map(int,input().split()))
a=list(map(int,input().split()))
d=[]
for i in range(n-1):
d.append(a[i]-a[i+1])
#print(*d)
t=n-1
for i in range(n-1):
if d[i]<0:
#print('i=',i)
f=0;g=0
if x>i:
r=i
else:
r=x
if y>n-1-i:
s=n-1-i
else:
s=y
for j in range(r):
#print('i-j-1=',i-j-1)
if d[i-j-1]<0:
f=1
break
#print(d[i-j-1])
for j in range(s-1):
#print('i+j+1=',i+j+1)
if d[i+j+1]>0:
g=1
break
#print(d[i+j+1])
if f==0 and g==0:
#print(a[i],d[i])
t=i
break
print(t+1)
```
No
| 98,706 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
For years, the Day of city N was held in the most rainy day of summer. New mayor decided to break this tradition and select a not-so-rainy day for the celebration. The mayor knows the weather forecast for the n days of summer. On the i-th day, a_i millimeters of rain will fall. All values a_i are distinct.
The mayor knows that citizens will watch the weather x days before the celebration and y days after. Because of that, he says that a day d is not-so-rainy if a_d is smaller than rain amounts at each of x days before day d and and each of y days after day d. In other words, a_d < a_j should hold for all d - x ≤ j < d and d < j ≤ d + y. Citizens only watch the weather during summer, so we only consider such j that 1 ≤ j ≤ n.
Help mayor find the earliest not-so-rainy day of summer.
Input
The first line contains three integers n, x and y (1 ≤ n ≤ 100 000, 0 ≤ x, y ≤ 7) — the number of days in summer, the number of days citizens watch the weather before the celebration and the number of days they do that after.
The second line contains n distinct integers a_1, a_2, ..., a_n (1 ≤ a_i ≤ 10^9), where a_i denotes the rain amount on the i-th day.
Output
Print a single integer — the index of the earliest not-so-rainy day of summer. We can show that the answer always exists.
Examples
Input
10 2 2
10 9 6 7 8 3 2 1 4 5
Output
3
Input
10 2 3
10 9 6 7 8 3 2 1 4 5
Output
8
Input
5 5 5
100000 10000 1000 100 10
Output
5
Note
In the first example days 3 and 8 are not-so-rainy. The 3-rd day is earlier.
In the second example day 3 is not not-so-rainy, because 3 + y = 6 and a_3 > a_6. Thus, day 8 is the answer. Note that 8 + y = 11, but we don't consider day 11, because it is not summer.
Submitted Solution:
```
from collections import deque
n, x, y = map(int, input().split())
arr = list(map(int, input().split()))
left_dq = deque()
right_dq = deque()
for i in range(1, y):
while right_dq and arr[right_dq[-1]] > arr[i]:
right_dq.pop()
right_dq.append(i)
ans = -1
for i in range(n):
while left_dq and left_dq[0] < i-x:
left_dq.popleft()
while right_dq and right_dq[0] <= i:
right_dq.popleft()
if i > 0:
while left_dq and arr[left_dq[-1]] > arr[i-1]:
left_dq.pop()
left_dq.append(i-1)
min_left = arr[left_dq[0]]
else:
min_left = float('inf')
if i+y < n:
while right_dq and arr[right_dq[-1]] > arr[i+y]:
right_dq.pop()
right_dq.append(i+y)
min_right = arr[right_dq[0]]
else:
min_right = arr[right_dq[0]] if right_dq else float('inf')
if arr[i] < min_left and arr[i] < min_right:
ans = i+1
break
print(ans)
```
No
| 98,707 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
For years, the Day of city N was held in the most rainy day of summer. New mayor decided to break this tradition and select a not-so-rainy day for the celebration. The mayor knows the weather forecast for the n days of summer. On the i-th day, a_i millimeters of rain will fall. All values a_i are distinct.
The mayor knows that citizens will watch the weather x days before the celebration and y days after. Because of that, he says that a day d is not-so-rainy if a_d is smaller than rain amounts at each of x days before day d and and each of y days after day d. In other words, a_d < a_j should hold for all d - x ≤ j < d and d < j ≤ d + y. Citizens only watch the weather during summer, so we only consider such j that 1 ≤ j ≤ n.
Help mayor find the earliest not-so-rainy day of summer.
Input
The first line contains three integers n, x and y (1 ≤ n ≤ 100 000, 0 ≤ x, y ≤ 7) — the number of days in summer, the number of days citizens watch the weather before the celebration and the number of days they do that after.
The second line contains n distinct integers a_1, a_2, ..., a_n (1 ≤ a_i ≤ 10^9), where a_i denotes the rain amount on the i-th day.
Output
Print a single integer — the index of the earliest not-so-rainy day of summer. We can show that the answer always exists.
Examples
Input
10 2 2
10 9 6 7 8 3 2 1 4 5
Output
3
Input
10 2 3
10 9 6 7 8 3 2 1 4 5
Output
8
Input
5 5 5
100000 10000 1000 100 10
Output
5
Note
In the first example days 3 and 8 are not-so-rainy. The 3-rd day is earlier.
In the second example day 3 is not not-so-rainy, because 3 + y = 6 and a_3 > a_6. Thus, day 8 is the answer. Note that 8 + y = 11, but we don't consider day 11, because it is not summer.
Submitted Solution:
```
'''
tìm vị trí sớm nhất mà lượng mưa nhỏ hơn x ngày trước và y ngày sau
'''
n,x,y=map(int,input().split(' '))
rainingday=list(map(int,input().split(' ')))
stack=[0]
left=[0 for i in range(n)]
right=[n-1 for i in range(n)]
for i in range(1,n):
while(len(stack)!=0 and rainingday[stack[-1]]>=rainingday[i]):
right[stack[-1]]=i-1
stack.pop()
if(len(stack)!=0):
left[i]=stack[-1]+1
else:
left[i]=0
stack.append(i)
for i in range(n):
if(i-left[i]>=x and right[i]-i>=y):
print(i+1)
break
elif((left[i]==0 or i-left[i]>x) and (right[i]==n-1 or right[i]-i>y)):
print(i+1)
break
```
No
| 98,708 |
Provide tags and a correct Python 3 solution for this coding contest problem.
In addition to complaints about lighting, a lot of complaints about insufficient radio signal covering has been received by Bertown city hall recently. n complaints were sent to the mayor, all of which are suspiciosly similar to each other: in the i-th complaint, one of the radio fans has mentioned that the signals of two radio stations x_i and y_i are not covering some parts of the city, and demanded that the signal of at least one of these stations can be received in the whole city.
Of cousre, the mayor of Bertown is currently working to satisfy these complaints. A new radio tower has been installed in Bertown, it can transmit a signal with any integer power from 1 to M (let's denote the signal power as f). The mayor has decided that he will choose a set of radio stations and establish a contract with every chosen station. To establish a contract with the i-th station, the following conditions should be met:
* the signal power f should be not less than l_i, otherwise the signal of the i-th station won't cover the whole city;
* the signal power f should be not greater than r_i, otherwise the signal will be received by the residents of other towns which haven't established a contract with the i-th station.
All this information was already enough for the mayor to realise that choosing the stations is hard. But after consulting with specialists, he learned that some stations the signals of some stations may interfere with each other: there are m pairs of stations (u_i, v_i) that use the same signal frequencies, and for each such pair it is impossible to establish contracts with both stations. If stations x and y use the same frequencies, and y and z use the same frequencies, it does not imply that x and z use the same frequencies.
The mayor finds it really hard to analyze this situation, so he hired you to help him. You have to choose signal power f and a set of stations to establish contracts with such that:
* all complaints are satisfied (formally, for every i ∈ [1, n] the city establishes a contract either with station x_i, or with station y_i);
* no two chosen stations interfere with each other (formally, for every i ∈ [1, m] the city does not establish a contract either with station u_i, or with station v_i);
* for each chosen station, the conditions on signal power are met (formally, for each chosen station i the condition l_i ≤ f ≤ r_i is met).
Input
The first line contains 4 integers n, p, M and m (2 ≤ n, p, M, m ≤ 4 ⋅ 10^5) — the number of complaints, the number of radio stations, maximum signal power and the number of interfering pairs, respectively.
Then n lines follow, which describe the complains. Each line contains two integers x_i and y_i (1 ≤ x_i < y_i ≤ p) — the indices of the radio stations mentioned in the i-th complaint). All complaints are distinct.
Then p lines follow, which describe the radio stations. Each line contains two integers l_i and r_i (1 ≤ l_i ≤ r_i ≤ M) — the constrains on signal power that should be satisfied if the city establishes a contract with the i-th station.
Then m lines follow, which describe the pairs of interfering radio stations. Each line contains two integers u_i and v_i (1 ≤ u_i < v_i ≤ p) — the indices of interfering radio stations. All these pairs are distinct.
Output
If it is impossible to choose signal power and a set of stations to meet all conditions, print -1.
Otherwise print two integers k and f in the first line — the number of stations in the chosen set and the chosen signal power, respectively. In the second line print k distinct integers from 1 to p — the indices of stations to establish contracts with (in any order). If there are multiple answers, print any of them; you don't have to minimize/maximize the number of chosen stations, and the same applies to signal power.
Examples
Input
2 4 4 2
1 3
2 3
1 4
1 2
3 4
1 4
1 2
3 4
Output
2 3
1 3
Input
2 4 4 2
1 3
2 4
1 2
1 2
3 4
3 4
1 2
3 4
Output
-1
Tags: 2-sat
Correct Solution:
```
# ------------------- fast io --------------------
import os
import sys
input = lambda: sys.stdin.readline().rstrip("\r\n")
# ------------------- fast io --------------------
def find_SCC(graph):
SCC, S, P = [], [], []
depth = [0] * len(graph)
stack = list(range(len(graph)))
while stack:
node = stack.pop()
if node < 0:
d = depth[~node] - 1
if P[-1] > d:
SCC.append(S[d:])
del S[d:], P[-1]
for node in SCC[-1]:
depth[node] = -1
elif depth[node] > 0:
while P[-1] > depth[node]:
P.pop()
elif depth[node] == 0:
S.append(node)
P.append(len(S))
depth[node] = len(S)
stack.append(~node)
stack += graph[node]
SCC = SCC[::-1]
cx = [-1] * (len(graph))
for i in range(len(SCC)):
for j in SCC[i]:
cx[j] = i
return cx
for _ in range(int(input()) if not True else 1):
# n = int(input())
n, p, M, m = map(int, input().split())
# a, b = map(int, input().split())
# c, d = map(int, input().split())
# a = list(map(int, input().split()))
# b = list(map(int, input().split()))
# s = input()
graph = [[] for __ in range(2 * p + 2 * M + 1)]
for i in range(n):
x, y = map(int, input().split())
x2 = (x + p)
y2 = (y + p)
graph[x2] += [y]
graph[y2] += [x]
for x in range(1, p + 1):
l, r = map(int, input().split())
x2 = (x + p)
l += 2 * p
r += 2 * p + 1
graph[l+M] += [x2]
graph[x] += [l]
if r + M != 2 * p + 2 * M + 1:
graph[r] += [x2]
graph[x] += [r + M]
for i in range(m):
x, y = map(int, input().split())
x2 = (x + p)
y2 = (y + p)
graph[x] += [y2]
graph[y] += [x2]
for i in range(1, M):
graph[2 * p + i + M] += [2 * p + i + M + 1]
graph[2 * p + i + 1] += [2 * p + i]
cx = find_SCC(graph)
ans = []
for i in range(1, p + 1):
if cx[i] > cx[i + p]:
ans += [i]
if not ans:
print(-1)
quit()
for freq in range(M, 0, -1):
if cx[2 * p + freq] > cx[2 * p + freq + M]:
break
print(len(ans), freq)
print(*ans)
```
| 98,709 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Recently Ivan the Fool decided to become smarter and study the probability theory. He thinks that he understands the subject fairly well, and so he began to behave like he already got PhD in that area.
To prove his skills, Ivan decided to demonstrate his friends a concept of random picture. A picture is a field of n rows and m columns, where each cell is either black or white. Ivan calls the picture random if for every cell it has at most one adjacent cell of the same color. Two cells are considered adjacent if they share a side.
Ivan's brothers spent some time trying to explain that it's not how the randomness usually works. Trying to convince Ivan, they want to count the number of different random (according to Ivan) pictures. Two pictures are considered different if at least one cell on those two picture is colored differently. Since the number of such pictures may be quite large, print it modulo 10^9 + 7.
Input
The only line contains two integers n and m (1 ≤ n, m ≤ 100 000), the number of rows and the number of columns of the field.
Output
Print one integer, the number of random pictures modulo 10^9 + 7.
Example
Input
2 3
Output
8
Note
The picture below shows all possible random pictures of size 2 by 3.
<image>
Tags: combinatorics, dp, math
Correct Solution:
```
from bisect import bisect_left as bl, bisect_right as br, insort
import sys
import heapq
#from math import *
from collections import defaultdict as dd, deque
def data(): return sys.stdin.readline().strip()
def mdata(): return map(int, data().split())
#def print(x): return sys.stdout.write(str(x)+'\n')
#sys.setrecursionlimit(100000)
mod=int(1e9+7)
n,m=mdata()
dp=[[2,0,0]]
for i in range(1,m):
dp.append([(2*dp[i-1][0]-dp[i-1][2]+mod)%mod,(dp[i-1][1]+dp[i-1][0]-dp[i-1][2]+mod)%mod,(dp[i-1][0]-dp[i-1][2]+mod)%mod])
cnt=dp[-1][1]
k1=dp[-1][0]-dp[-1][1]
k2=0
for i in range(1,n):
k1,k2=(2*k1-k2+mod)%mod,(k1-k2+mod)%mod
print((cnt+k1)%mod)
```
| 98,710 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Recently Ivan the Fool decided to become smarter and study the probability theory. He thinks that he understands the subject fairly well, and so he began to behave like he already got PhD in that area.
To prove his skills, Ivan decided to demonstrate his friends a concept of random picture. A picture is a field of n rows and m columns, where each cell is either black or white. Ivan calls the picture random if for every cell it has at most one adjacent cell of the same color. Two cells are considered adjacent if they share a side.
Ivan's brothers spent some time trying to explain that it's not how the randomness usually works. Trying to convince Ivan, they want to count the number of different random (according to Ivan) pictures. Two pictures are considered different if at least one cell on those two picture is colored differently. Since the number of such pictures may be quite large, print it modulo 10^9 + 7.
Input
The only line contains two integers n and m (1 ≤ n, m ≤ 100 000), the number of rows and the number of columns of the field.
Output
Print one integer, the number of random pictures modulo 10^9 + 7.
Example
Input
2 3
Output
8
Note
The picture below shows all possible random pictures of size 2 by 3.
<image>
Tags: combinatorics, dp, math
Correct Solution:
```
n, m = [int(i) for i in input().split()]
mod = 1000000007
def fib(number):
a, b = 1, 1
for i in range(number):
a, b = b, (a + b) % mod
return a
print(2 * (fib(n) + fib(m) - 1) % mod)
```
| 98,711 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Recently Ivan the Fool decided to become smarter and study the probability theory. He thinks that he understands the subject fairly well, and so he began to behave like he already got PhD in that area.
To prove his skills, Ivan decided to demonstrate his friends a concept of random picture. A picture is a field of n rows and m columns, where each cell is either black or white. Ivan calls the picture random if for every cell it has at most one adjacent cell of the same color. Two cells are considered adjacent if they share a side.
Ivan's brothers spent some time trying to explain that it's not how the randomness usually works. Trying to convince Ivan, they want to count the number of different random (according to Ivan) pictures. Two pictures are considered different if at least one cell on those two picture is colored differently. Since the number of such pictures may be quite large, print it modulo 10^9 + 7.
Input
The only line contains two integers n and m (1 ≤ n, m ≤ 100 000), the number of rows and the number of columns of the field.
Output
Print one integer, the number of random pictures modulo 10^9 + 7.
Example
Input
2 3
Output
8
Note
The picture below shows all possible random pictures of size 2 by 3.
<image>
Tags: combinatorics, dp, math
Correct Solution:
```
from sys import stdin
input = stdin.readline
MOD = 1_000_000_007
n, m = [int(x) for x in input().split()]
dp = [1, 1]
for i in range(max(n, m) + 1):
dp.append((dp[-2] + dp[-1]) % MOD)
x = dp[m] * 2
y = dp[n] * 2
ans = (x + y - 2) % MOD
print(ans)
```
| 98,712 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Recently Ivan the Fool decided to become smarter and study the probability theory. He thinks that he understands the subject fairly well, and so he began to behave like he already got PhD in that area.
To prove his skills, Ivan decided to demonstrate his friends a concept of random picture. A picture is a field of n rows and m columns, where each cell is either black or white. Ivan calls the picture random if for every cell it has at most one adjacent cell of the same color. Two cells are considered adjacent if they share a side.
Ivan's brothers spent some time trying to explain that it's not how the randomness usually works. Trying to convince Ivan, they want to count the number of different random (according to Ivan) pictures. Two pictures are considered different if at least one cell on those two picture is colored differently. Since the number of such pictures may be quite large, print it modulo 10^9 + 7.
Input
The only line contains two integers n and m (1 ≤ n, m ≤ 100 000), the number of rows and the number of columns of the field.
Output
Print one integer, the number of random pictures modulo 10^9 + 7.
Example
Input
2 3
Output
8
Note
The picture below shows all possible random pictures of size 2 by 3.
<image>
Tags: combinatorics, dp, math
Correct Solution:
```
modulo = 1000000007
inline = [int(x) for x in input().split(' ')]
row = max(inline[0], inline[1])
col = min(inline[0], inline[1])
if row > 1 and col > 1:
rowrec = [0] * row
rowrec[0] = 2
rowrec[1] = 4
for i in range(2, row):
rowrec[i] = (rowrec[i-1]+rowrec[i-2]) % modulo
colrec = [0]*col
colrec[0] = rowrec[row-1]
colrec[1] = 2+colrec[0]
for i in range(2, col):
colrec[i] = (colrec[i-1] + rowrec[i-2]) % modulo
print(colrec[col-1])
else:
theOne = max(row, col)
rowrec = [0] * theOne
if theOne == 1:
print(2)
else:
rowrec[0] = 2
rowrec[1] = 4
for i in range(2, theOne):
rowrec[i] = (rowrec[i - 1] + rowrec[i - 2]) % modulo
print(rowrec[theOne-1])
```
| 98,713 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Recently Ivan the Fool decided to become smarter and study the probability theory. He thinks that he understands the subject fairly well, and so he began to behave like he already got PhD in that area.
To prove his skills, Ivan decided to demonstrate his friends a concept of random picture. A picture is a field of n rows and m columns, where each cell is either black or white. Ivan calls the picture random if for every cell it has at most one adjacent cell of the same color. Two cells are considered adjacent if they share a side.
Ivan's brothers spent some time trying to explain that it's not how the randomness usually works. Trying to convince Ivan, they want to count the number of different random (according to Ivan) pictures. Two pictures are considered different if at least one cell on those two picture is colored differently. Since the number of such pictures may be quite large, print it modulo 10^9 + 7.
Input
The only line contains two integers n and m (1 ≤ n, m ≤ 100 000), the number of rows and the number of columns of the field.
Output
Print one integer, the number of random pictures modulo 10^9 + 7.
Example
Input
2 3
Output
8
Note
The picture below shows all possible random pictures of size 2 by 3.
<image>
Tags: combinatorics, dp, math
Correct Solution:
```
import os
import sys
from io import BytesIO, IOBase
# region fastio
BUFSIZE = 8192
class FastIO(IOBase):
newlines = 0
def __init__(self, file):
self._fd = file.fileno()
self.buffer = BytesIO()
self.writable = "x" in file.mode or "r" not in file.mode
self.write = self.buffer.write if self.writable else None
def read(self):
while True:
b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
if not b:
break
ptr = self.buffer.tell()
self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr)
self.newlines = 0
return self.buffer.read()
def readline(self):
while self.newlines == 0:
b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
self.newlines = b.count(b"\n") + (not b)
ptr = self.buffer.tell()
self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr)
self.newlines -= 1
return self.buffer.readline()
def flush(self):
if self.writable:
os.write(self._fd, self.buffer.getvalue())
self.buffer.truncate(0), self.buffer.seek(0)
class IOWrapper(IOBase):
def __init__(self, file):
self.buffer = FastIO(file)
self.flush = self.buffer.flush
self.writable = self.buffer.writable
self.write = lambda s: self.buffer.write(s.encode("ascii"))
self.read = lambda: self.buffer.read().decode("ascii")
self.readline = lambda: self.buffer.readline().decode("ascii")
sys.stdin, sys.stdout = IOWrapper(sys.stdin), IOWrapper(sys.stdout)
input = lambda: sys.stdin.readline().rstrip("\r\n")
# ------------------------------
def RL(): return map(int, sys.stdin.readline().rstrip().split())
def RLL(): return list(map(int, sys.stdin.readline().rstrip().split()))
def N(): return int(input())
def comb(n, m): return factorial(n) / (factorial(m) * factorial(n - m)) if n >= m else 0
def perm(n, m): return factorial(n) // (factorial(n - m)) if n >= m else 0
def mdis(x1, y1, x2, y2): return abs(x1 - x2) + abs(y1 - y2)
def toord(c): return ord(c)-ord('a')
def lcm(a, b): return a*b//lcm(a, b)
mod = 10**9+7
INF = float('inf')
from math import factorial, sqrt, ceil, floor, gcd
from collections import Counter, defaultdict, deque
from heapq import heapify, heappop, heappush
# ------------------------------
# f = open('./input.txt')
# sys.stdin = f
def main():
n, m = RL()
if n<m: n, m = m, n
dp = [[0, 0] for _ in range(n+1)]
dp[1] = [1, 1]
dp[0] = [1, 1]
for i in range(2, n+1):
dp[i][0] = max(dp[i][1], (dp[i-1][1]+dp[i-2][1])%mod)
dp[i][1] = max(dp[i][0], (dp[i-1][0]+dp[i-2][0])%mod)
# print(dp)
print((sum(dp[m]) + sum(dp[n]) - 2)%mod)
if __name__ == "__main__":
main()
```
| 98,714 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Recently Ivan the Fool decided to become smarter and study the probability theory. He thinks that he understands the subject fairly well, and so he began to behave like he already got PhD in that area.
To prove his skills, Ivan decided to demonstrate his friends a concept of random picture. A picture is a field of n rows and m columns, where each cell is either black or white. Ivan calls the picture random if for every cell it has at most one adjacent cell of the same color. Two cells are considered adjacent if they share a side.
Ivan's brothers spent some time trying to explain that it's not how the randomness usually works. Trying to convince Ivan, they want to count the number of different random (according to Ivan) pictures. Two pictures are considered different if at least one cell on those two picture is colored differently. Since the number of such pictures may be quite large, print it modulo 10^9 + 7.
Input
The only line contains two integers n and m (1 ≤ n, m ≤ 100 000), the number of rows and the number of columns of the field.
Output
Print one integer, the number of random pictures modulo 10^9 + 7.
Example
Input
2 3
Output
8
Note
The picture below shows all possible random pictures of size 2 by 3.
<image>
Tags: combinatorics, dp, math
Correct Solution:
```
# by the authority of GOD author: manhar singh sachdev #
import os,sys
from io import BytesIO, IOBase
mod = 10**9+7
def solve(x):
dp = [[0,0] for _ in range(x)]
# same ; different
dp[0] = [0,2]
for i in range(1,x):
dp[i][0] = (dp[i][0]+dp[i-1][1])%mod
dp[i][1] = (dp[i][1]+dp[i-1][0]+dp[i-1][1])%mod
return (dp[x-1][0]+dp[x-1][1])%mod
def main():
n,m = map(int,input().split())
print((solve(n)+solve(m)-2)%mod)
# Fast IO Region
BUFSIZE = 8192
class FastIO(IOBase):
newlines = 0
def __init__(self, file):
self._fd = file.fileno()
self.buffer = BytesIO()
self.writable = "x" in file.mode or "r" not in file.mode
self.write = self.buffer.write if self.writable else None
def read(self):
while True:
b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
if not b:
break
ptr = self.buffer.tell()
self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr)
self.newlines = 0
return self.buffer.read()
def readline(self):
while self.newlines == 0:
b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
self.newlines = b.count(b"\n") + (not b)
ptr = self.buffer.tell()
self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr)
self.newlines -= 1
return self.buffer.readline()
def flush(self):
if self.writable:
os.write(self._fd, self.buffer.getvalue())
self.buffer.truncate(0), self.buffer.seek(0)
class IOWrapper(IOBase):
def __init__(self, file):
self.buffer = FastIO(file)
self.flush = self.buffer.flush
self.writable = self.buffer.writable
self.write = lambda s: self.buffer.write(s.encode("ascii"))
self.read = lambda: self.buffer.read().decode("ascii")
self.readline = lambda: self.buffer.readline().decode("ascii")
sys.stdin, sys.stdout = IOWrapper(sys.stdin), IOWrapper(sys.stdout)
input = lambda: sys.stdin.readline().rstrip("\r\n")
if __name__ == "__main__":
main()
```
| 98,715 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Recently Ivan the Fool decided to become smarter and study the probability theory. He thinks that he understands the subject fairly well, and so he began to behave like he already got PhD in that area.
To prove his skills, Ivan decided to demonstrate his friends a concept of random picture. A picture is a field of n rows and m columns, where each cell is either black or white. Ivan calls the picture random if for every cell it has at most one adjacent cell of the same color. Two cells are considered adjacent if they share a side.
Ivan's brothers spent some time trying to explain that it's not how the randomness usually works. Trying to convince Ivan, they want to count the number of different random (according to Ivan) pictures. Two pictures are considered different if at least one cell on those two picture is colored differently. Since the number of such pictures may be quite large, print it modulo 10^9 + 7.
Input
The only line contains two integers n and m (1 ≤ n, m ≤ 100 000), the number of rows and the number of columns of the field.
Output
Print one integer, the number of random pictures modulo 10^9 + 7.
Example
Input
2 3
Output
8
Note
The picture below shows all possible random pictures of size 2 by 3.
<image>
Tags: combinatorics, dp, math
Correct Solution:
```
n,m=map(int,input().split())
mod=10**9+7
B=[1]
W=[1]
BB=[0]
WW=[0]
for i in range(1,100010):
x=W[-1]+WW[-1]
y=B[-1]+BB[-1]
z=B[-1]
w=W[-1]
x%=mod
y%=mod
z%=mod
w%=mod
B.append(x)
W.append(y)
BB.append(z)
WW.append(w)
print((B[n-1]+W[n-1]+BB[n-1]+WW[n-1]+B[m-1]+W[m-1]+BB[m-1]+WW[m-1]-2)%mod)
```
| 98,716 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Recently Ivan the Fool decided to become smarter and study the probability theory. He thinks that he understands the subject fairly well, and so he began to behave like he already got PhD in that area.
To prove his skills, Ivan decided to demonstrate his friends a concept of random picture. A picture is a field of n rows and m columns, where each cell is either black or white. Ivan calls the picture random if for every cell it has at most one adjacent cell of the same color. Two cells are considered adjacent if they share a side.
Ivan's brothers spent some time trying to explain that it's not how the randomness usually works. Trying to convince Ivan, they want to count the number of different random (according to Ivan) pictures. Two pictures are considered different if at least one cell on those two picture is colored differently. Since the number of such pictures may be quite large, print it modulo 10^9 + 7.
Input
The only line contains two integers n and m (1 ≤ n, m ≤ 100 000), the number of rows and the number of columns of the field.
Output
Print one integer, the number of random pictures modulo 10^9 + 7.
Example
Input
2 3
Output
8
Note
The picture below shows all possible random pictures of size 2 by 3.
<image>
Tags: combinatorics, dp, math
Correct Solution:
```
n, m = map(int, input().split())
d = [2, 4]
k = 10**9+7
for i in range(2, max(n, m)):
d += [(d[i-1]+d[i-2]) % k]
print((d[m-1]+d[n-1]-2) % k)
```
| 98,717 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Recently Ivan the Fool decided to become smarter and study the probability theory. He thinks that he understands the subject fairly well, and so he began to behave like he already got PhD in that area.
To prove his skills, Ivan decided to demonstrate his friends a concept of random picture. A picture is a field of n rows and m columns, where each cell is either black or white. Ivan calls the picture random if for every cell it has at most one adjacent cell of the same color. Two cells are considered adjacent if they share a side.
Ivan's brothers spent some time trying to explain that it's not how the randomness usually works. Trying to convince Ivan, they want to count the number of different random (according to Ivan) pictures. Two pictures are considered different if at least one cell on those two picture is colored differently. Since the number of such pictures may be quite large, print it modulo 10^9 + 7.
Input
The only line contains two integers n and m (1 ≤ n, m ≤ 100 000), the number of rows and the number of columns of the field.
Output
Print one integer, the number of random pictures modulo 10^9 + 7.
Example
Input
2 3
Output
8
Note
The picture below shows all possible random pictures of size 2 by 3.
<image>
Submitted Solution:
```
# Legends Always Come Up with Solution
# Author: Manvir Singh
import os
import sys
from io import BytesIO, IOBase
mod=10**9+7
def solve(x):
dp=[[0,0] for _ in range(x+1)]
dp[1]=[1,1]
dp[0]=[1,1]
for i in range(2,x+1):
dp[i][0]=(dp[i-2][1]+dp[i-1][1])%mod
dp[i][1]=(dp[i-2][0]+dp[i-1][0])%mod
return (dp[-1][0]+dp[-1][1])%mod
def main():
n,m=map(int,input().split())
print((solve(n)+solve(m)-2)%mod)
# region fastio
BUFSIZE = 8192
class FastIO(IOBase):
newlines = 0
def __init__(self, file):
self._fd = file.fileno()
self.buffer = BytesIO()
self.writable = "x" in file.mode or "r" not in file.mode
self.write = self.buffer.write if self.writable else None
def read(self):
while True:
b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
if not b:
break
ptr = self.buffer.tell()
self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr)
self.newlines = 0
return self.buffer.read()
def readline(self):
while self.newlines == 0:
b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
self.newlines = b.count(b"\n") + (not b)
ptr = self.buffer.tell()
self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr)
self.newlines -= 1
return self.buffer.readline()
def flush(self):
if self.writable:
os.write(self._fd, self.buffer.getvalue())
self.buffer.truncate(0), self.buffer.seek(0)
class IOWrapper(IOBase):
def __init__(self, file):
self.buffer = FastIO(file)
self.flush = self.buffer.flush
self.writable = self.buffer.writable
self.write = lambda s: self.buffer.write(s.encode("ascii"))
self.read = lambda: self.buffer.read().decode("ascii")
self.readline = lambda: self.buffer.readline().decode("ascii")
sys.stdin, sys.stdout = IOWrapper(sys.stdin), IOWrapper(sys.stdout)
input = lambda: sys.stdin.readline().rstrip("\r\n")
if __name__ == "__main__":
main()
```
Yes
| 98,718 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Recently Ivan the Fool decided to become smarter and study the probability theory. He thinks that he understands the subject fairly well, and so he began to behave like he already got PhD in that area.
To prove his skills, Ivan decided to demonstrate his friends a concept of random picture. A picture is a field of n rows and m columns, where each cell is either black or white. Ivan calls the picture random if for every cell it has at most one adjacent cell of the same color. Two cells are considered adjacent if they share a side.
Ivan's brothers spent some time trying to explain that it's not how the randomness usually works. Trying to convince Ivan, they want to count the number of different random (according to Ivan) pictures. Two pictures are considered different if at least one cell on those two picture is colored differently. Since the number of such pictures may be quite large, print it modulo 10^9 + 7.
Input
The only line contains two integers n and m (1 ≤ n, m ≤ 100 000), the number of rows and the number of columns of the field.
Output
Print one integer, the number of random pictures modulo 10^9 + 7.
Example
Input
2 3
Output
8
Note
The picture below shows all possible random pictures of size 2 by 3.
<image>
Submitted Solution:
```
from sys import stdin
def input():
return stdin.readline()[:-1]
def intput():
return int(input())
def sinput():
return input().split()
def intsput():
return map(int, sinput())
mod = 10 ** 9 + 7
n, m = intsput()
fib = [2, 2]
for _ in range(100001):
fib.append((fib[-1] + fib[-2]) % mod)
print((fib[n] + fib[m] - 2) % mod)
```
Yes
| 98,719 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Recently Ivan the Fool decided to become smarter and study the probability theory. He thinks that he understands the subject fairly well, and so he began to behave like he already got PhD in that area.
To prove his skills, Ivan decided to demonstrate his friends a concept of random picture. A picture is a field of n rows and m columns, where each cell is either black or white. Ivan calls the picture random if for every cell it has at most one adjacent cell of the same color. Two cells are considered adjacent if they share a side.
Ivan's brothers spent some time trying to explain that it's not how the randomness usually works. Trying to convince Ivan, they want to count the number of different random (according to Ivan) pictures. Two pictures are considered different if at least one cell on those two picture is colored differently. Since the number of such pictures may be quite large, print it modulo 10^9 + 7.
Input
The only line contains two integers n and m (1 ≤ n, m ≤ 100 000), the number of rows and the number of columns of the field.
Output
Print one integer, the number of random pictures modulo 10^9 + 7.
Example
Input
2 3
Output
8
Note
The picture below shows all possible random pictures of size 2 by 3.
<image>
Submitted Solution:
```
import sys
input = sys.stdin.readline
n, m = map(int, input().split())
if n == 1 and m == 1:
print(2)
exit()
MOD = 10**9+7
N = max(n, m)
dp = [[0] * 4 for _ in range(N+1)]
for j in range(4):
dp[2][j] = 1
for i in range(2, N):
dp[i+1][0] = dp[i][2]
dp[i+1][1] = dp[i][0]+dp[i][2]
dp[i+1][2] = dp[i][1]+dp[i][3]
dp[i+1][3] = dp[i][1]
for j in range(4):
dp[i+1][j] %= MOD
if n == 1:
print(sum(dp[m])%MOD)
elif m == 1:
print(sum(dp[n])%MOD)
else:
print((sum(dp[n])+sum(dp[m])-2)%MOD)
```
Yes
| 98,720 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Recently Ivan the Fool decided to become smarter and study the probability theory. He thinks that he understands the subject fairly well, and so he began to behave like he already got PhD in that area.
To prove his skills, Ivan decided to demonstrate his friends a concept of random picture. A picture is a field of n rows and m columns, where each cell is either black or white. Ivan calls the picture random if for every cell it has at most one adjacent cell of the same color. Two cells are considered adjacent if they share a side.
Ivan's brothers spent some time trying to explain that it's not how the randomness usually works. Trying to convince Ivan, they want to count the number of different random (according to Ivan) pictures. Two pictures are considered different if at least one cell on those two picture is colored differently. Since the number of such pictures may be quite large, print it modulo 10^9 + 7.
Input
The only line contains two integers n and m (1 ≤ n, m ≤ 100 000), the number of rows and the number of columns of the field.
Output
Print one integer, the number of random pictures modulo 10^9 + 7.
Example
Input
2 3
Output
8
Note
The picture below shows all possible random pictures of size 2 by 3.
<image>
Submitted Solution:
```
n,m=[int(x) for x in input().split()]
dp=[0]*100001
dp[0]=2
dp[1]=2
dp[2]=4
for i in range(3,100001):
dp[i]=(dp[i-1]*2-dp[i-3])%(10**9+7)
print((dp[n]+dp[m]-2)%(10**9+7))
```
Yes
| 98,721 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Recently Ivan the Fool decided to become smarter and study the probability theory. He thinks that he understands the subject fairly well, and so he began to behave like he already got PhD in that area.
To prove his skills, Ivan decided to demonstrate his friends a concept of random picture. A picture is a field of n rows and m columns, where each cell is either black or white. Ivan calls the picture random if for every cell it has at most one adjacent cell of the same color. Two cells are considered adjacent if they share a side.
Ivan's brothers spent some time trying to explain that it's not how the randomness usually works. Trying to convince Ivan, they want to count the number of different random (according to Ivan) pictures. Two pictures are considered different if at least one cell on those two picture is colored differently. Since the number of such pictures may be quite large, print it modulo 10^9 + 7.
Input
The only line contains two integers n and m (1 ≤ n, m ≤ 100 000), the number of rows and the number of columns of the field.
Output
Print one integer, the number of random pictures modulo 10^9 + 7.
Example
Input
2 3
Output
8
Note
The picture below shows all possible random pictures of size 2 by 3.
<image>
Submitted Solution:
```
a, b = map(int, input().split())
first = b // 2
second = b - first * 2
print(pow(2, first * ((a + 1) // 2) + second * (a // 2), 10 ** 9 + 7))
```
No
| 98,722 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Recently Ivan the Fool decided to become smarter and study the probability theory. He thinks that he understands the subject fairly well, and so he began to behave like he already got PhD in that area.
To prove his skills, Ivan decided to demonstrate his friends a concept of random picture. A picture is a field of n rows and m columns, where each cell is either black or white. Ivan calls the picture random if for every cell it has at most one adjacent cell of the same color. Two cells are considered adjacent if they share a side.
Ivan's brothers spent some time trying to explain that it's not how the randomness usually works. Trying to convince Ivan, they want to count the number of different random (according to Ivan) pictures. Two pictures are considered different if at least one cell on those two picture is colored differently. Since the number of such pictures may be quite large, print it modulo 10^9 + 7.
Input
The only line contains two integers n and m (1 ≤ n, m ≤ 100 000), the number of rows and the number of columns of the field.
Output
Print one integer, the number of random pictures modulo 10^9 + 7.
Example
Input
2 3
Output
8
Note
The picture below shows all possible random pictures of size 2 by 3.
<image>
Submitted Solution:
```
a, b = map(int,input().split())
mod = 10**9+7
ans = 0
for n in [a,b]:
A = [[0,0] for i in range(n)]
A[0] = [0,1]
if n > 1:
A[1] = [1,1]
for i in range(2,n):
A[i][0] = A[i-2][1] % mod
A[i][1] = sum(A[i-1]) % mod
# print(A)
ans += (sum(A[-1]) * 2) % mod
print((ans-2) % mod)
```
No
| 98,723 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Recently Ivan the Fool decided to become smarter and study the probability theory. He thinks that he understands the subject fairly well, and so he began to behave like he already got PhD in that area.
To prove his skills, Ivan decided to demonstrate his friends a concept of random picture. A picture is a field of n rows and m columns, where each cell is either black or white. Ivan calls the picture random if for every cell it has at most one adjacent cell of the same color. Two cells are considered adjacent if they share a side.
Ivan's brothers spent some time trying to explain that it's not how the randomness usually works. Trying to convince Ivan, they want to count the number of different random (according to Ivan) pictures. Two pictures are considered different if at least one cell on those two picture is colored differently. Since the number of such pictures may be quite large, print it modulo 10^9 + 7.
Input
The only line contains two integers n and m (1 ≤ n, m ≤ 100 000), the number of rows and the number of columns of the field.
Output
Print one integer, the number of random pictures modulo 10^9 + 7.
Example
Input
2 3
Output
8
Note
The picture below shows all possible random pictures of size 2 by 3.
<image>
Submitted Solution:
```
''' CODED WITH LOVE BY SATYAM KUMAR '''
from sys import stdin, stdout
import heapq
import cProfile, math
from collections import Counter, defaultdict, deque
from bisect import bisect_left, bisect, bisect_right
import itertools
from copy import deepcopy
from fractions import Fraction
import sys, threading
import operator as op
from functools import reduce
import sys
sys.setrecursionlimit(10 ** 6) # max depth of recursion
threading.stack_size(2 ** 27) # new thread will get stack of such size
fac_warm_up = False
printHeap = str()
memory_constrained = False
P = 10 ** 9 + 7
class MergeFind:
def __init__(self, n):
self.parent = list(range(n))
self.size = [1] * n
self.num_sets = n
self.lista = [[_] for _ in range(n)]
def find(self, a):
to_update = []
while a != self.parent[a]:
to_update.append(a)
a = self.parent[a]
for b in to_update:
self.parent[b] = a
return self.parent[a]
def merge(self, a, b):
a = self.find(a)
b = self.find(b)
if a == b:
return
if self.size[a] < self.size[b]:
a, b = b, a
self.num_sets -= 1
self.parent[b] = a
self.size[a] += self.size[b]
self.lista[a] += self.lista[b]
def set_size(self, a):
return self.size[self.find(a)]
def __len__(self):
return self.num_sets
def display(string_to_print):
stdout.write(str(string_to_print) + "\n")
def prime_factors(n): # n**0.5 complex
factors = dict()
for i in range(2, math.ceil(math.sqrt(n)) + 1):
while n % i == 0:
if i in factors:
factors[i] += 1
else:
factors[i] = 1
n = n // i
if n > 2:
factors[n] = 1
return (factors)
def all_factors(n):
return set(reduce(list.__add__,
([i, n // i] for i in range(1, int(n ** 0.5) + 1) if n % i == 0)))
def fibonacci_modP(n, MOD):
if n < 2: return 1
return (cached_fn(fibonacci_modP, (n + 1) // 2, MOD) * cached_fn(fibonacci_modP, n // 2, MOD) + cached_fn(
fibonacci_modP, (n - 1) // 2, MOD) * cached_fn(fibonacci_modP, (n - 2) // 2, MOD)) % MOD
def factorial_modP_Wilson(n, p):
if (p <= n):
return 0
res = (p - 1)
for i in range(n + 1, p):
res = (res * cached_fn(InverseEuler, i, p)) % p
return res
def binary(n, digits=20):
b = bin(n)[2:]
b = '0' * (digits - len(b)) + b
return b
def is_prime(n):
"""Returns True if n is prime."""
if n < 4:
return True
if n % 2 == 0:
return False
if n % 3 == 0:
return False
i = 5
w = 2
while i * i <= n:
if n % i == 0:
return False
i += w
w = 6 - w
return True
def generate_primes(n):
prime = [True for i in range(n + 1)]
p = 2
while p * p <= n:
if prime[p]:
for i in range(p * 2, n + 1, p):
prime[i] = False
p += 1
return prime
factorial_modP = []
def warm_up_fac(MOD):
global factorial_modP, fac_warm_up
if fac_warm_up: return
factorial_modP = [1 for _ in range(fac_warm_up_size + 1)]
for i in range(2, fac_warm_up_size):
factorial_modP[i] = (factorial_modP[i - 1] * i) % MOD
fac_warm_up = True
def InverseEuler(n, MOD):
return pow(n, MOD - 2, MOD)
def nCr(n, r, MOD):
global fac_warm_up, factorial_modP
if not fac_warm_up:
warm_up_fac(MOD)
fac_warm_up = True
return (factorial_modP[n] * (
(pow(factorial_modP[r], MOD - 2, MOD) * pow(factorial_modP[n - r], MOD - 2, MOD)) % MOD)) % MOD
def get_int():
return int(stdin.readline().strip())
def get_tuple():
return map(int, stdin.readline().split())
def get_list():
return list(map(int, stdin.readline().split()))
memory = dict()
def clear_cache():
global memory
memory = dict()
def cached_fn(fn, *args):
global memory
if args in memory:
return memory[args]
else:
result = fn(*args)
memory[args] = result
return result
def ncr(n, r):
return math.factorial(n) / (math.factorial(n - r) * math.factorial(r))
def binary_search(i, li):
fn = lambda x: li[x] - x // i
x = -1
b = len(li)
while b >= 1:
while b + x < len(li) and fn(b + x) > 0: # Change this condition 2 to whatever you like
x += b
b = b // 2
return x
# -------------------------------------------------------------- MAIN PROGRAM
TestCases = False
optimise_for_recursion = True # Can not be used clubbed with TestCases WHen using recursive functions, use Python 3
def main():
n, m = get_tuple()
p, q = 1, 1
r1 = 1
for i in range(1, n):
r1 = p + q
p = q
q = r1
p, q = 1, 1
r2 = 1
for i in range(1, m):
r2 = p + q
p = q
q = r2
#print(r1, r2)
print(2*(r1+r2-1))
# --------------------------------------------------------------------- END=
if TestCases:
for i in range(get_int()):
main()
else:
main() if not optimise_for_recursion else threading.Thread(target=main).start()
```
No
| 98,724 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Recently Ivan the Fool decided to become smarter and study the probability theory. He thinks that he understands the subject fairly well, and so he began to behave like he already got PhD in that area.
To prove his skills, Ivan decided to demonstrate his friends a concept of random picture. A picture is a field of n rows and m columns, where each cell is either black or white. Ivan calls the picture random if for every cell it has at most one adjacent cell of the same color. Two cells are considered adjacent if they share a side.
Ivan's brothers spent some time trying to explain that it's not how the randomness usually works. Trying to convince Ivan, they want to count the number of different random (according to Ivan) pictures. Two pictures are considered different if at least one cell on those two picture is colored differently. Since the number of such pictures may be quite large, print it modulo 10^9 + 7.
Input
The only line contains two integers n and m (1 ≤ n, m ≤ 100 000), the number of rows and the number of columns of the field.
Output
Print one integer, the number of random pictures modulo 10^9 + 7.
Example
Input
2 3
Output
8
Note
The picture below shows all possible random pictures of size 2 by 3.
<image>
Submitted Solution:
```
n, m = map(int, input().split())
b = n*m + 2
print(b%(10**9+7))
```
No
| 98,725 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Let's call an array t dominated by value v in the next situation.
At first, array t should have at least 2 elements. Now, let's calculate number of occurrences of each number num in t and define it as occ(num). Then t is dominated (by v) if (and only if) occ(v) > occ(v') for any other number v'. For example, arrays [1, 2, 3, 4, 5, 2], [11, 11] and [3, 2, 3, 2, 3] are dominated (by 2, 11 and 3 respectevitely) but arrays [3], [1, 2] and [3, 3, 2, 2, 1] are not.
Small remark: since any array can be dominated only by one number, we can not specify this number and just say that array is either dominated or not.
You are given array a_1, a_2, ..., a_n. Calculate its shortest dominated subarray or say that there are no such subarrays.
The subarray of a is a contiguous part of the array a, i. e. the array a_i, a_{i + 1}, ..., a_j for some 1 ≤ i ≤ j ≤ n.
Input
The first line contains single integer T (1 ≤ T ≤ 1000) — the number of test cases. Each test case consists of two lines.
The first line contains single integer n (1 ≤ n ≤ 2 ⋅ 10^5) — the length of the array a.
The second line contains n integers a_1, a_2, ..., a_n (1 ≤ a_i ≤ n) — the corresponding values of the array a.
It's guaranteed that the total length of all arrays in one test doesn't exceed 2 ⋅ 10^5.
Output
Print T integers — one per test case. For each test case print the only integer — the length of the shortest dominated subarray, or -1 if there are no such subarrays.
Example
Input
4
1
1
6
1 2 3 4 5 1
9
4 1 2 4 5 4 3 2 1
4
3 3 3 3
Output
-1
6
3
2
Note
In the first test case, there are no subarrays of length at least 2, so the answer is -1.
In the second test case, the whole array is dominated (by 1) and it's the only dominated subarray.
In the third test case, the subarray a_4, a_5, a_6 is the shortest dominated subarray.
In the fourth test case, all subarrays of length more than one are dominated.
Tags: greedy, implementation, sortings, strings, two pointers
Correct Solution:
```
tc = int(input())
for ii in range(tc):
n = int(input())
ar = list(map(int,input().split()))
if n==1:
print(-1)
continue
x = dict()
m = float('inf')
c = 0
for i in range(n):
if ar[i] in x:
dif = i-x[ar[i]]
m = min(m,dif)
c = 1
x[ar[i]] = i
else:
x[ar[i]] = i
if c==0:
print(-1)
else:
print(m+1)
```
| 98,726 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Let's call an array t dominated by value v in the next situation.
At first, array t should have at least 2 elements. Now, let's calculate number of occurrences of each number num in t and define it as occ(num). Then t is dominated (by v) if (and only if) occ(v) > occ(v') for any other number v'. For example, arrays [1, 2, 3, 4, 5, 2], [11, 11] and [3, 2, 3, 2, 3] are dominated (by 2, 11 and 3 respectevitely) but arrays [3], [1, 2] and [3, 3, 2, 2, 1] are not.
Small remark: since any array can be dominated only by one number, we can not specify this number and just say that array is either dominated or not.
You are given array a_1, a_2, ..., a_n. Calculate its shortest dominated subarray or say that there are no such subarrays.
The subarray of a is a contiguous part of the array a, i. e. the array a_i, a_{i + 1}, ..., a_j for some 1 ≤ i ≤ j ≤ n.
Input
The first line contains single integer T (1 ≤ T ≤ 1000) — the number of test cases. Each test case consists of two lines.
The first line contains single integer n (1 ≤ n ≤ 2 ⋅ 10^5) — the length of the array a.
The second line contains n integers a_1, a_2, ..., a_n (1 ≤ a_i ≤ n) — the corresponding values of the array a.
It's guaranteed that the total length of all arrays in one test doesn't exceed 2 ⋅ 10^5.
Output
Print T integers — one per test case. For each test case print the only integer — the length of the shortest dominated subarray, or -1 if there are no such subarrays.
Example
Input
4
1
1
6
1 2 3 4 5 1
9
4 1 2 4 5 4 3 2 1
4
3 3 3 3
Output
-1
6
3
2
Note
In the first test case, there are no subarrays of length at least 2, so the answer is -1.
In the second test case, the whole array is dominated (by 1) and it's the only dominated subarray.
In the third test case, the subarray a_4, a_5, a_6 is the shortest dominated subarray.
In the fourth test case, all subarrays of length more than one are dominated.
Tags: greedy, implementation, sortings, strings, two pointers
Correct Solution:
```
import math
t=int(input())
for _ in range(t):
n=int(input())
a=list(map(int,input().split()))
d={}
ans=math.inf
for i in range(n):
if a[i] not in d:
d[a[i]]=i
else:
ans=min(ans,i-d[a[i]]+1)
d[a[i]]=i
if ans==math.inf:
print(-1)
else:
print(ans)
```
| 98,727 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Let's call an array t dominated by value v in the next situation.
At first, array t should have at least 2 elements. Now, let's calculate number of occurrences of each number num in t and define it as occ(num). Then t is dominated (by v) if (and only if) occ(v) > occ(v') for any other number v'. For example, arrays [1, 2, 3, 4, 5, 2], [11, 11] and [3, 2, 3, 2, 3] are dominated (by 2, 11 and 3 respectevitely) but arrays [3], [1, 2] and [3, 3, 2, 2, 1] are not.
Small remark: since any array can be dominated only by one number, we can not specify this number and just say that array is either dominated or not.
You are given array a_1, a_2, ..., a_n. Calculate its shortest dominated subarray or say that there are no such subarrays.
The subarray of a is a contiguous part of the array a, i. e. the array a_i, a_{i + 1}, ..., a_j for some 1 ≤ i ≤ j ≤ n.
Input
The first line contains single integer T (1 ≤ T ≤ 1000) — the number of test cases. Each test case consists of two lines.
The first line contains single integer n (1 ≤ n ≤ 2 ⋅ 10^5) — the length of the array a.
The second line contains n integers a_1, a_2, ..., a_n (1 ≤ a_i ≤ n) — the corresponding values of the array a.
It's guaranteed that the total length of all arrays in one test doesn't exceed 2 ⋅ 10^5.
Output
Print T integers — one per test case. For each test case print the only integer — the length of the shortest dominated subarray, or -1 if there are no such subarrays.
Example
Input
4
1
1
6
1 2 3 4 5 1
9
4 1 2 4 5 4 3 2 1
4
3 3 3 3
Output
-1
6
3
2
Note
In the first test case, there are no subarrays of length at least 2, so the answer is -1.
In the second test case, the whole array is dominated (by 1) and it's the only dominated subarray.
In the third test case, the subarray a_4, a_5, a_6 is the shortest dominated subarray.
In the fourth test case, all subarrays of length more than one are dominated.
Tags: greedy, implementation, sortings, strings, two pointers
Correct Solution:
```
t = int(input())
while t != 0:
n = int(input())
l = list(map(int, input().strip().split()))
dic = {}
for index, i in enumerate(l):
if i not in dic:
dic[i] = list()
dic[i].append(index)
continue
dic[i].append(index)
mini = 999999999
flag = False
for i in dic:
lx = list()
lx = dic[i]
if len(lx) != 1:
flag = True
for x in range(0, len(lx)-1):
mini = min(mini, lx[x+1]-lx[x])
if flag: print(mini+1)
else: print(-1)
t -= 1
```
| 98,728 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Let's call an array t dominated by value v in the next situation.
At first, array t should have at least 2 elements. Now, let's calculate number of occurrences of each number num in t and define it as occ(num). Then t is dominated (by v) if (and only if) occ(v) > occ(v') for any other number v'. For example, arrays [1, 2, 3, 4, 5, 2], [11, 11] and [3, 2, 3, 2, 3] are dominated (by 2, 11 and 3 respectevitely) but arrays [3], [1, 2] and [3, 3, 2, 2, 1] are not.
Small remark: since any array can be dominated only by one number, we can not specify this number and just say that array is either dominated or not.
You are given array a_1, a_2, ..., a_n. Calculate its shortest dominated subarray or say that there are no such subarrays.
The subarray of a is a contiguous part of the array a, i. e. the array a_i, a_{i + 1}, ..., a_j for some 1 ≤ i ≤ j ≤ n.
Input
The first line contains single integer T (1 ≤ T ≤ 1000) — the number of test cases. Each test case consists of two lines.
The first line contains single integer n (1 ≤ n ≤ 2 ⋅ 10^5) — the length of the array a.
The second line contains n integers a_1, a_2, ..., a_n (1 ≤ a_i ≤ n) — the corresponding values of the array a.
It's guaranteed that the total length of all arrays in one test doesn't exceed 2 ⋅ 10^5.
Output
Print T integers — one per test case. For each test case print the only integer — the length of the shortest dominated subarray, or -1 if there are no such subarrays.
Example
Input
4
1
1
6
1 2 3 4 5 1
9
4 1 2 4 5 4 3 2 1
4
3 3 3 3
Output
-1
6
3
2
Note
In the first test case, there are no subarrays of length at least 2, so the answer is -1.
In the second test case, the whole array is dominated (by 1) and it's the only dominated subarray.
In the third test case, the subarray a_4, a_5, a_6 is the shortest dominated subarray.
In the fourth test case, all subarrays of length more than one are dominated.
Tags: greedy, implementation, sortings, strings, two pointers
Correct Solution:
```
t = int(input())
for i in range(t):
n = int(input())
nums = list(map(int, input().split()))
i = 0
j = 0
min_len = 100010
sub = set()
while i < n and j < n:
sub_len = len(sub)
sub.add(nums[j])
if len(sub) == sub_len:
min_len = min(min_len, sub_len + 1)
sub.remove(nums[i])
i += 1
else:
j += 1
if min_len == 100010:
print(-1)
else:
print(min_len)
```
| 98,729 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Let's call an array t dominated by value v in the next situation.
At first, array t should have at least 2 elements. Now, let's calculate number of occurrences of each number num in t and define it as occ(num). Then t is dominated (by v) if (and only if) occ(v) > occ(v') for any other number v'. For example, arrays [1, 2, 3, 4, 5, 2], [11, 11] and [3, 2, 3, 2, 3] are dominated (by 2, 11 and 3 respectevitely) but arrays [3], [1, 2] and [3, 3, 2, 2, 1] are not.
Small remark: since any array can be dominated only by one number, we can not specify this number and just say that array is either dominated or not.
You are given array a_1, a_2, ..., a_n. Calculate its shortest dominated subarray or say that there are no such subarrays.
The subarray of a is a contiguous part of the array a, i. e. the array a_i, a_{i + 1}, ..., a_j for some 1 ≤ i ≤ j ≤ n.
Input
The first line contains single integer T (1 ≤ T ≤ 1000) — the number of test cases. Each test case consists of two lines.
The first line contains single integer n (1 ≤ n ≤ 2 ⋅ 10^5) — the length of the array a.
The second line contains n integers a_1, a_2, ..., a_n (1 ≤ a_i ≤ n) — the corresponding values of the array a.
It's guaranteed that the total length of all arrays in one test doesn't exceed 2 ⋅ 10^5.
Output
Print T integers — one per test case. For each test case print the only integer — the length of the shortest dominated subarray, or -1 if there are no such subarrays.
Example
Input
4
1
1
6
1 2 3 4 5 1
9
4 1 2 4 5 4 3 2 1
4
3 3 3 3
Output
-1
6
3
2
Note
In the first test case, there are no subarrays of length at least 2, so the answer is -1.
In the second test case, the whole array is dominated (by 1) and it's the only dominated subarray.
In the third test case, the subarray a_4, a_5, a_6 is the shortest dominated subarray.
In the fourth test case, all subarrays of length more than one are dominated.
Tags: greedy, implementation, sortings, strings, two pointers
Correct Solution:
```
for _ in range(int(input())):
n = int(input())
a = list(map(int, input().split()))
mark = [-1]*(200001)
dist = 200001
for i in range(n):
if mark[a[i]] == -1:
mark[a[i]] = i
else:
temp = i - mark[a[i]]
if temp >= 1:
dist = min(temp, dist)
mark[a[i]] = i
if dist == 200001:
print("-1")
continue
print(dist+1)
```
| 98,730 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Let's call an array t dominated by value v in the next situation.
At first, array t should have at least 2 elements. Now, let's calculate number of occurrences of each number num in t and define it as occ(num). Then t is dominated (by v) if (and only if) occ(v) > occ(v') for any other number v'. For example, arrays [1, 2, 3, 4, 5, 2], [11, 11] and [3, 2, 3, 2, 3] are dominated (by 2, 11 and 3 respectevitely) but arrays [3], [1, 2] and [3, 3, 2, 2, 1] are not.
Small remark: since any array can be dominated only by one number, we can not specify this number and just say that array is either dominated or not.
You are given array a_1, a_2, ..., a_n. Calculate its shortest dominated subarray or say that there are no such subarrays.
The subarray of a is a contiguous part of the array a, i. e. the array a_i, a_{i + 1}, ..., a_j for some 1 ≤ i ≤ j ≤ n.
Input
The first line contains single integer T (1 ≤ T ≤ 1000) — the number of test cases. Each test case consists of two lines.
The first line contains single integer n (1 ≤ n ≤ 2 ⋅ 10^5) — the length of the array a.
The second line contains n integers a_1, a_2, ..., a_n (1 ≤ a_i ≤ n) — the corresponding values of the array a.
It's guaranteed that the total length of all arrays in one test doesn't exceed 2 ⋅ 10^5.
Output
Print T integers — one per test case. For each test case print the only integer — the length of the shortest dominated subarray, or -1 if there are no such subarrays.
Example
Input
4
1
1
6
1 2 3 4 5 1
9
4 1 2 4 5 4 3 2 1
4
3 3 3 3
Output
-1
6
3
2
Note
In the first test case, there are no subarrays of length at least 2, so the answer is -1.
In the second test case, the whole array is dominated (by 1) and it's the only dominated subarray.
In the third test case, the subarray a_4, a_5, a_6 is the shortest dominated subarray.
In the fourth test case, all subarrays of length more than one are dominated.
Tags: greedy, implementation, sortings, strings, two pointers
Correct Solution:
```
a = int(input())
for i in range(a):
b = int(input())
lst = list(map(int, input().split()))
c = b+1
d = [-1]*(b+1)
for t in range(b):
if d[lst[t]] != -1:
c = min(c, t-d[lst[t]]+1)
d[lst[t]] = t
if c > b:
c = -1
print(c)
```
| 98,731 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Let's call an array t dominated by value v in the next situation.
At first, array t should have at least 2 elements. Now, let's calculate number of occurrences of each number num in t and define it as occ(num). Then t is dominated (by v) if (and only if) occ(v) > occ(v') for any other number v'. For example, arrays [1, 2, 3, 4, 5, 2], [11, 11] and [3, 2, 3, 2, 3] are dominated (by 2, 11 and 3 respectevitely) but arrays [3], [1, 2] and [3, 3, 2, 2, 1] are not.
Small remark: since any array can be dominated only by one number, we can not specify this number and just say that array is either dominated or not.
You are given array a_1, a_2, ..., a_n. Calculate its shortest dominated subarray or say that there are no such subarrays.
The subarray of a is a contiguous part of the array a, i. e. the array a_i, a_{i + 1}, ..., a_j for some 1 ≤ i ≤ j ≤ n.
Input
The first line contains single integer T (1 ≤ T ≤ 1000) — the number of test cases. Each test case consists of two lines.
The first line contains single integer n (1 ≤ n ≤ 2 ⋅ 10^5) — the length of the array a.
The second line contains n integers a_1, a_2, ..., a_n (1 ≤ a_i ≤ n) — the corresponding values of the array a.
It's guaranteed that the total length of all arrays in one test doesn't exceed 2 ⋅ 10^5.
Output
Print T integers — one per test case. For each test case print the only integer — the length of the shortest dominated subarray, or -1 if there are no such subarrays.
Example
Input
4
1
1
6
1 2 3 4 5 1
9
4 1 2 4 5 4 3 2 1
4
3 3 3 3
Output
-1
6
3
2
Note
In the first test case, there are no subarrays of length at least 2, so the answer is -1.
In the second test case, the whole array is dominated (by 1) and it's the only dominated subarray.
In the third test case, the subarray a_4, a_5, a_6 is the shortest dominated subarray.
In the fourth test case, all subarrays of length more than one are dominated.
Tags: greedy, implementation, sortings, strings, two pointers
Correct Solution:
```
import sys
input = sys.stdin.readline
t = int(input())
for _ in range(t):
n = int(input())
a = list(map(int, input().split()))
li = {}
for i in range(n):
if a[i] not in li:
li[a[i]] = [i]
else:
li[a[i]].append(i)
ans = 10**9
for num in li:
tmp = li[num]
for j in range(len(tmp) - 1):
ans = min(ans, tmp[j+1] - tmp[j] + 1)
if ans == 10**9:
print(-1)
else:
print(ans)
```
| 98,732 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Let's call an array t dominated by value v in the next situation.
At first, array t should have at least 2 elements. Now, let's calculate number of occurrences of each number num in t and define it as occ(num). Then t is dominated (by v) if (and only if) occ(v) > occ(v') for any other number v'. For example, arrays [1, 2, 3, 4, 5, 2], [11, 11] and [3, 2, 3, 2, 3] are dominated (by 2, 11 and 3 respectevitely) but arrays [3], [1, 2] and [3, 3, 2, 2, 1] are not.
Small remark: since any array can be dominated only by one number, we can not specify this number and just say that array is either dominated or not.
You are given array a_1, a_2, ..., a_n. Calculate its shortest dominated subarray or say that there are no such subarrays.
The subarray of a is a contiguous part of the array a, i. e. the array a_i, a_{i + 1}, ..., a_j for some 1 ≤ i ≤ j ≤ n.
Input
The first line contains single integer T (1 ≤ T ≤ 1000) — the number of test cases. Each test case consists of two lines.
The first line contains single integer n (1 ≤ n ≤ 2 ⋅ 10^5) — the length of the array a.
The second line contains n integers a_1, a_2, ..., a_n (1 ≤ a_i ≤ n) — the corresponding values of the array a.
It's guaranteed that the total length of all arrays in one test doesn't exceed 2 ⋅ 10^5.
Output
Print T integers — one per test case. For each test case print the only integer — the length of the shortest dominated subarray, or -1 if there are no such subarrays.
Example
Input
4
1
1
6
1 2 3 4 5 1
9
4 1 2 4 5 4 3 2 1
4
3 3 3 3
Output
-1
6
3
2
Note
In the first test case, there are no subarrays of length at least 2, so the answer is -1.
In the second test case, the whole array is dominated (by 1) and it's the only dominated subarray.
In the third test case, the subarray a_4, a_5, a_6 is the shortest dominated subarray.
In the fourth test case, all subarrays of length more than one are dominated.
Tags: greedy, implementation, sortings, strings, two pointers
Correct Solution:
```
T = int(input())
results = []
for i in range(T):
n = int(input())
vals = input().split()
a = [int(val) for val in vals]
if len(a) < 2:
results.append(-1)
else:
d = {}
minLen = -1
# key: number, val: lastPos
for i in range(n):
a_i = a[i]
if a_i in d:
if minLen == -1:
minLen = i - d[a_i] + 1
else:
minLen = min(minLen, i - d[a_i] + 1)
d[a_i] = i
results.append(minLen)
for result in results:
print(result)
```
| 98,733 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Let's call an array t dominated by value v in the next situation.
At first, array t should have at least 2 elements. Now, let's calculate number of occurrences of each number num in t and define it as occ(num). Then t is dominated (by v) if (and only if) occ(v) > occ(v') for any other number v'. For example, arrays [1, 2, 3, 4, 5, 2], [11, 11] and [3, 2, 3, 2, 3] are dominated (by 2, 11 and 3 respectevitely) but arrays [3], [1, 2] and [3, 3, 2, 2, 1] are not.
Small remark: since any array can be dominated only by one number, we can not specify this number and just say that array is either dominated or not.
You are given array a_1, a_2, ..., a_n. Calculate its shortest dominated subarray or say that there are no such subarrays.
The subarray of a is a contiguous part of the array a, i. e. the array a_i, a_{i + 1}, ..., a_j for some 1 ≤ i ≤ j ≤ n.
Input
The first line contains single integer T (1 ≤ T ≤ 1000) — the number of test cases. Each test case consists of two lines.
The first line contains single integer n (1 ≤ n ≤ 2 ⋅ 10^5) — the length of the array a.
The second line contains n integers a_1, a_2, ..., a_n (1 ≤ a_i ≤ n) — the corresponding values of the array a.
It's guaranteed that the total length of all arrays in one test doesn't exceed 2 ⋅ 10^5.
Output
Print T integers — one per test case. For each test case print the only integer — the length of the shortest dominated subarray, or -1 if there are no such subarrays.
Example
Input
4
1
1
6
1 2 3 4 5 1
9
4 1 2 4 5 4 3 2 1
4
3 3 3 3
Output
-1
6
3
2
Note
In the first test case, there are no subarrays of length at least 2, so the answer is -1.
In the second test case, the whole array is dominated (by 1) and it's the only dominated subarray.
In the third test case, the subarray a_4, a_5, a_6 is the shortest dominated subarray.
In the fourth test case, all subarrays of length more than one are dominated.
Submitted Solution:
```
for _ in range(int(input())):
n=int(input())
d={}
a=list(map(int,input().split()))
if n==1:
print(-1)
else:
ans=2*(10**5)
p=[None]*(n+1)
for i in range(1,n+1):
if p[a[i-1]]==None:
p[a[i-1]]=i
else:
ans=min(ans,i-p[a[i-1]]+1)
p[a[i-1]]=i
if ans == 2*(10**5):
print(-1)
else:
print(ans)
```
Yes
| 98,734 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Let's call an array t dominated by value v in the next situation.
At first, array t should have at least 2 elements. Now, let's calculate number of occurrences of each number num in t and define it as occ(num). Then t is dominated (by v) if (and only if) occ(v) > occ(v') for any other number v'. For example, arrays [1, 2, 3, 4, 5, 2], [11, 11] and [3, 2, 3, 2, 3] are dominated (by 2, 11 and 3 respectevitely) but arrays [3], [1, 2] and [3, 3, 2, 2, 1] are not.
Small remark: since any array can be dominated only by one number, we can not specify this number and just say that array is either dominated or not.
You are given array a_1, a_2, ..., a_n. Calculate its shortest dominated subarray or say that there are no such subarrays.
The subarray of a is a contiguous part of the array a, i. e. the array a_i, a_{i + 1}, ..., a_j for some 1 ≤ i ≤ j ≤ n.
Input
The first line contains single integer T (1 ≤ T ≤ 1000) — the number of test cases. Each test case consists of two lines.
The first line contains single integer n (1 ≤ n ≤ 2 ⋅ 10^5) — the length of the array a.
The second line contains n integers a_1, a_2, ..., a_n (1 ≤ a_i ≤ n) — the corresponding values of the array a.
It's guaranteed that the total length of all arrays in one test doesn't exceed 2 ⋅ 10^5.
Output
Print T integers — one per test case. For each test case print the only integer — the length of the shortest dominated subarray, or -1 if there are no such subarrays.
Example
Input
4
1
1
6
1 2 3 4 5 1
9
4 1 2 4 5 4 3 2 1
4
3 3 3 3
Output
-1
6
3
2
Note
In the first test case, there are no subarrays of length at least 2, so the answer is -1.
In the second test case, the whole array is dominated (by 1) and it's the only dominated subarray.
In the third test case, the subarray a_4, a_5, a_6 is the shortest dominated subarray.
In the fourth test case, all subarrays of length more than one are dominated.
Submitted Solution:
```
import sys
input = sys.stdin.readline
INF = 10**15
Q = int(input())
Query = []
for _ in range(Q):
N = int(input())
A = list(map(int, input().split()))
Query.append((N, A))
for N, A in Query:
ans = INF
dic = {}
for i, a in enumerate(A):
if a in dic:
ans = min(ans, i-dic[a]+1)
dic[a] = i
else:
dic[a] = i
if ans == INF:
ans = -1
print(ans)
```
Yes
| 98,735 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Let's call an array t dominated by value v in the next situation.
At first, array t should have at least 2 elements. Now, let's calculate number of occurrences of each number num in t and define it as occ(num). Then t is dominated (by v) if (and only if) occ(v) > occ(v') for any other number v'. For example, arrays [1, 2, 3, 4, 5, 2], [11, 11] and [3, 2, 3, 2, 3] are dominated (by 2, 11 and 3 respectevitely) but arrays [3], [1, 2] and [3, 3, 2, 2, 1] are not.
Small remark: since any array can be dominated only by one number, we can not specify this number and just say that array is either dominated or not.
You are given array a_1, a_2, ..., a_n. Calculate its shortest dominated subarray or say that there are no such subarrays.
The subarray of a is a contiguous part of the array a, i. e. the array a_i, a_{i + 1}, ..., a_j for some 1 ≤ i ≤ j ≤ n.
Input
The first line contains single integer T (1 ≤ T ≤ 1000) — the number of test cases. Each test case consists of two lines.
The first line contains single integer n (1 ≤ n ≤ 2 ⋅ 10^5) — the length of the array a.
The second line contains n integers a_1, a_2, ..., a_n (1 ≤ a_i ≤ n) — the corresponding values of the array a.
It's guaranteed that the total length of all arrays in one test doesn't exceed 2 ⋅ 10^5.
Output
Print T integers — one per test case. For each test case print the only integer — the length of the shortest dominated subarray, or -1 if there are no such subarrays.
Example
Input
4
1
1
6
1 2 3 4 5 1
9
4 1 2 4 5 4 3 2 1
4
3 3 3 3
Output
-1
6
3
2
Note
In the first test case, there are no subarrays of length at least 2, so the answer is -1.
In the second test case, the whole array is dominated (by 1) and it's the only dominated subarray.
In the third test case, the subarray a_4, a_5, a_6 is the shortest dominated subarray.
In the fourth test case, all subarrays of length more than one are dominated.
Submitted Solution:
```
import sys
from collections import defaultdict
t = int(input())
for kkk in range(t):
n = int(sys.stdin.readline())
a = list(map(int ,sys.stdin.readline().split()))
d = defaultdict(int)
m = n+1
for i in range(len(a)):
if d[a[i]] == 0:
d[a[i]] = i+1
else:
m = min(m, i - d[a[i]] + 2)
d[a[i]] = i+1
if m == n+1:
print(-1)
else:
print(m)
```
Yes
| 98,736 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Let's call an array t dominated by value v in the next situation.
At first, array t should have at least 2 elements. Now, let's calculate number of occurrences of each number num in t and define it as occ(num). Then t is dominated (by v) if (and only if) occ(v) > occ(v') for any other number v'. For example, arrays [1, 2, 3, 4, 5, 2], [11, 11] and [3, 2, 3, 2, 3] are dominated (by 2, 11 and 3 respectevitely) but arrays [3], [1, 2] and [3, 3, 2, 2, 1] are not.
Small remark: since any array can be dominated only by one number, we can not specify this number and just say that array is either dominated or not.
You are given array a_1, a_2, ..., a_n. Calculate its shortest dominated subarray or say that there are no such subarrays.
The subarray of a is a contiguous part of the array a, i. e. the array a_i, a_{i + 1}, ..., a_j for some 1 ≤ i ≤ j ≤ n.
Input
The first line contains single integer T (1 ≤ T ≤ 1000) — the number of test cases. Each test case consists of two lines.
The first line contains single integer n (1 ≤ n ≤ 2 ⋅ 10^5) — the length of the array a.
The second line contains n integers a_1, a_2, ..., a_n (1 ≤ a_i ≤ n) — the corresponding values of the array a.
It's guaranteed that the total length of all arrays in one test doesn't exceed 2 ⋅ 10^5.
Output
Print T integers — one per test case. For each test case print the only integer — the length of the shortest dominated subarray, or -1 if there are no such subarrays.
Example
Input
4
1
1
6
1 2 3 4 5 1
9
4 1 2 4 5 4 3 2 1
4
3 3 3 3
Output
-1
6
3
2
Note
In the first test case, there are no subarrays of length at least 2, so the answer is -1.
In the second test case, the whole array is dominated (by 1) and it's the only dominated subarray.
In the third test case, the subarray a_4, a_5, a_6 is the shortest dominated subarray.
In the fourth test case, all subarrays of length more than one are dominated.
Submitted Solution:
```
t=int(input())
for tst in range(t):
n=int(input())
l=list(map(int,input().split()))
mini=float("inf")
d={}
if len(l)<2:
print(-1)
else:
for i in range(n):
if l[i] not in d:
d[l[i]]=i
#print(d)
else:
mini=min(i-d[l[i]]+1,mini)
d[l[i]]=i
#print(d,"555555")
if mini!=float("inf"):
print(mini)
else:
print(-1)
```
Yes
| 98,737 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Let's call an array t dominated by value v in the next situation.
At first, array t should have at least 2 elements. Now, let's calculate number of occurrences of each number num in t and define it as occ(num). Then t is dominated (by v) if (and only if) occ(v) > occ(v') for any other number v'. For example, arrays [1, 2, 3, 4, 5, 2], [11, 11] and [3, 2, 3, 2, 3] are dominated (by 2, 11 and 3 respectevitely) but arrays [3], [1, 2] and [3, 3, 2, 2, 1] are not.
Small remark: since any array can be dominated only by one number, we can not specify this number and just say that array is either dominated or not.
You are given array a_1, a_2, ..., a_n. Calculate its shortest dominated subarray or say that there are no such subarrays.
The subarray of a is a contiguous part of the array a, i. e. the array a_i, a_{i + 1}, ..., a_j for some 1 ≤ i ≤ j ≤ n.
Input
The first line contains single integer T (1 ≤ T ≤ 1000) — the number of test cases. Each test case consists of two lines.
The first line contains single integer n (1 ≤ n ≤ 2 ⋅ 10^5) — the length of the array a.
The second line contains n integers a_1, a_2, ..., a_n (1 ≤ a_i ≤ n) — the corresponding values of the array a.
It's guaranteed that the total length of all arrays in one test doesn't exceed 2 ⋅ 10^5.
Output
Print T integers — one per test case. For each test case print the only integer — the length of the shortest dominated subarray, or -1 if there are no such subarrays.
Example
Input
4
1
1
6
1 2 3 4 5 1
9
4 1 2 4 5 4 3 2 1
4
3 3 3 3
Output
-1
6
3
2
Note
In the first test case, there are no subarrays of length at least 2, so the answer is -1.
In the second test case, the whole array is dominated (by 1) and it's the only dominated subarray.
In the third test case, the subarray a_4, a_5, a_6 is the shortest dominated subarray.
In the fourth test case, all subarrays of length more than one are dominated.
Submitted Solution:
```
for _ in range(int(input())):
n = int(input())
a = list(map(int,input().split()))
d = dict()
dup = False
mx = 1
mx_index = -1
if len(a)>=2:
for i in range(len(a)):
num = a[i]
if num not in d:
d[num] = [i]
else:
d[num].append(i)
for i in d.keys():
l = len(d[i])
if l>mx:
dup = False
mx = l
mx_index = i
elif l==mx:
dup = True
if dup==True or mx==1:
print(-1)
else:
m = 100000000
for i in range(mx-1):
m = min(d[mx_index][i+1]-d[mx_index][i]+1, m)
print(m)
else:
print(-1)
```
No
| 98,738 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Let's call an array t dominated by value v in the next situation.
At first, array t should have at least 2 elements. Now, let's calculate number of occurrences of each number num in t and define it as occ(num). Then t is dominated (by v) if (and only if) occ(v) > occ(v') for any other number v'. For example, arrays [1, 2, 3, 4, 5, 2], [11, 11] and [3, 2, 3, 2, 3] are dominated (by 2, 11 and 3 respectevitely) but arrays [3], [1, 2] and [3, 3, 2, 2, 1] are not.
Small remark: since any array can be dominated only by one number, we can not specify this number and just say that array is either dominated or not.
You are given array a_1, a_2, ..., a_n. Calculate its shortest dominated subarray or say that there are no such subarrays.
The subarray of a is a contiguous part of the array a, i. e. the array a_i, a_{i + 1}, ..., a_j for some 1 ≤ i ≤ j ≤ n.
Input
The first line contains single integer T (1 ≤ T ≤ 1000) — the number of test cases. Each test case consists of two lines.
The first line contains single integer n (1 ≤ n ≤ 2 ⋅ 10^5) — the length of the array a.
The second line contains n integers a_1, a_2, ..., a_n (1 ≤ a_i ≤ n) — the corresponding values of the array a.
It's guaranteed that the total length of all arrays in one test doesn't exceed 2 ⋅ 10^5.
Output
Print T integers — one per test case. For each test case print the only integer — the length of the shortest dominated subarray, or -1 if there are no such subarrays.
Example
Input
4
1
1
6
1 2 3 4 5 1
9
4 1 2 4 5 4 3 2 1
4
3 3 3 3
Output
-1
6
3
2
Note
In the first test case, there are no subarrays of length at least 2, so the answer is -1.
In the second test case, the whole array is dominated (by 1) and it's the only dominated subarray.
In the third test case, the subarray a_4, a_5, a_6 is the shortest dominated subarray.
In the fourth test case, all subarrays of length more than one are dominated.
Submitted Solution:
```
t=int(input())
for k in range(t):
n=int(input())
count=n
arr=list(map(int,input().split()))
if len(arr)==1:
print(-1)
elif len(arr)==2:
if arr[0]==arr[1]:
print(2)
else:
print(-1)
else:
i = 0
j = n-1
while i<n-1:
if arr[j] == arr[i]:
count = min(count, j + 1 - i)
j -= 1
else:
j -= 1
if j == i:
j = n - 1
i += 1
if count<n:
print(count)
else:
print(-1)
```
No
| 98,739 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Let's call an array t dominated by value v in the next situation.
At first, array t should have at least 2 elements. Now, let's calculate number of occurrences of each number num in t and define it as occ(num). Then t is dominated (by v) if (and only if) occ(v) > occ(v') for any other number v'. For example, arrays [1, 2, 3, 4, 5, 2], [11, 11] and [3, 2, 3, 2, 3] are dominated (by 2, 11 and 3 respectevitely) but arrays [3], [1, 2] and [3, 3, 2, 2, 1] are not.
Small remark: since any array can be dominated only by one number, we can not specify this number and just say that array is either dominated or not.
You are given array a_1, a_2, ..., a_n. Calculate its shortest dominated subarray or say that there are no such subarrays.
The subarray of a is a contiguous part of the array a, i. e. the array a_i, a_{i + 1}, ..., a_j for some 1 ≤ i ≤ j ≤ n.
Input
The first line contains single integer T (1 ≤ T ≤ 1000) — the number of test cases. Each test case consists of two lines.
The first line contains single integer n (1 ≤ n ≤ 2 ⋅ 10^5) — the length of the array a.
The second line contains n integers a_1, a_2, ..., a_n (1 ≤ a_i ≤ n) — the corresponding values of the array a.
It's guaranteed that the total length of all arrays in one test doesn't exceed 2 ⋅ 10^5.
Output
Print T integers — one per test case. For each test case print the only integer — the length of the shortest dominated subarray, or -1 if there are no such subarrays.
Example
Input
4
1
1
6
1 2 3 4 5 1
9
4 1 2 4 5 4 3 2 1
4
3 3 3 3
Output
-1
6
3
2
Note
In the first test case, there are no subarrays of length at least 2, so the answer is -1.
In the second test case, the whole array is dominated (by 1) and it's the only dominated subarray.
In the third test case, the subarray a_4, a_5, a_6 is the shortest dominated subarray.
In the fourth test case, all subarrays of length more than one are dominated.
Submitted Solution:
```
for x in range(int(input())):
n = int(input())
a = [int(x) for x in input().split()]
b = [0] * (n + 5)
if n == 1:
print(-1)
continue
for x in a:
b[x] += 1
mx = b.index(max(b))
b.sort()
if b[len(b) - 1] == b[len(b) - 2]:
print(-1)
else:
ans = n + 5
j = -1
for i in range(n):
if a[i] == mx:
if j != -1:
ans = min(ans, i - j + 1)
j = i
print(ans)
```
No
| 98,740 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Let's call an array t dominated by value v in the next situation.
At first, array t should have at least 2 elements. Now, let's calculate number of occurrences of each number num in t and define it as occ(num). Then t is dominated (by v) if (and only if) occ(v) > occ(v') for any other number v'. For example, arrays [1, 2, 3, 4, 5, 2], [11, 11] and [3, 2, 3, 2, 3] are dominated (by 2, 11 and 3 respectevitely) but arrays [3], [1, 2] and [3, 3, 2, 2, 1] are not.
Small remark: since any array can be dominated only by one number, we can not specify this number and just say that array is either dominated or not.
You are given array a_1, a_2, ..., a_n. Calculate its shortest dominated subarray or say that there are no such subarrays.
The subarray of a is a contiguous part of the array a, i. e. the array a_i, a_{i + 1}, ..., a_j for some 1 ≤ i ≤ j ≤ n.
Input
The first line contains single integer T (1 ≤ T ≤ 1000) — the number of test cases. Each test case consists of two lines.
The first line contains single integer n (1 ≤ n ≤ 2 ⋅ 10^5) — the length of the array a.
The second line contains n integers a_1, a_2, ..., a_n (1 ≤ a_i ≤ n) — the corresponding values of the array a.
It's guaranteed that the total length of all arrays in one test doesn't exceed 2 ⋅ 10^5.
Output
Print T integers — one per test case. For each test case print the only integer — the length of the shortest dominated subarray, or -1 if there are no such subarrays.
Example
Input
4
1
1
6
1 2 3 4 5 1
9
4 1 2 4 5 4 3 2 1
4
3 3 3 3
Output
-1
6
3
2
Note
In the first test case, there are no subarrays of length at least 2, so the answer is -1.
In the second test case, the whole array is dominated (by 1) and it's the only dominated subarray.
In the third test case, the subarray a_4, a_5, a_6 is the shortest dominated subarray.
In the fourth test case, all subarrays of length more than one are dominated.
Submitted Solution:
```
t = int(input())
for ti in range(t):
l=int(input())
arr=[int(i) for i in input().split(" ")]
if l==1:
print(-1)
continue
mx=1
tg=0
masterKey=-1
curlen=9999999999
minlen=9999999999
di={}
for j in range(len(arr)):
if arr[j] in di:
di[arr[j]]+=1
if di[arr[j]]>mx:
mx=di[arr[j]]
masterKey=arr[j]
tg=0
elif di[arr[j]]==mx:
tg=1
else:
di[arr[j]]=1
if tg:
print(-1)
continue
if mx==1:
print(-1)
continue
cd={}
cdm=1
masnum=1
for j in arr:
if masterKey==j:
curlen+=1
if curlen<minlen and cdm<=masnum:
minlen=curlen
elif masnum<cdm:
masnum+=1
else:
curlen=1
cd={}
cdm=1
else:
if j in cd:
cd[j]+=1
if cdm<cd[j]:
cdm=cd[j]
else:
cd[j]=1
curlen+=1
#print(di)
if minlen>l:
print(-1)
continue
print(minlen)
```
No
| 98,741 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Anu has created her own function f: f(x, y) = (x | y) - y where | denotes the [bitwise OR operation](https://en.wikipedia.org/wiki/Bitwise_operation#OR). For example, f(11, 6) = (11|6) - 6 = 15 - 6 = 9. It can be proved that for any nonnegative numbers x and y value of f(x, y) is also nonnegative.
She would like to research more about this function and has created multiple problems for herself. But she isn't able to solve all of them and needs your help. Here is one of these problems.
A value of an array [a_1, a_2, ..., a_n] is defined as f(f(... f(f(a_1, a_2), a_3), ... a_{n-1}), a_n) (see notes). You are given an array with not necessarily distinct elements. How should you reorder its elements so that the value of the array is maximal possible?
Input
The first line contains a single integer n (1 ≤ n ≤ 10^5).
The second line contains n integers a_1, a_2, …, a_n (0 ≤ a_i ≤ 10^9). Elements of the array are not guaranteed to be different.
Output
Output n integers, the reordering of the array with maximum value. If there are multiple answers, print any.
Examples
Input
4
4 0 11 6
Output
11 6 4 0
Input
1
13
Output
13
Note
In the first testcase, value of the array [11, 6, 4, 0] is f(f(f(11, 6), 4), 0) = f(f(9, 4), 0) = f(9, 0) = 9.
[11, 4, 0, 6] is also a valid answer.
Tags: brute force, greedy, math
Correct Solution:
```
n = int(input())
a = list(map(int,input().split()))
bitFreq = [0] * 32
for i in a :
for j in range(0,32):
if (i & (1 << j)) > 0 :
bitFreq[j] += 1
currBest = 0
currIn = 0
for i in range(len(a)):
currScore = 0
for j in range(0,32):
if (a[i] & (1 << j)) > 0 and bitFreq[j] == 1:
currScore = (currScore | 1 << j)
if currScore > currBest:
currBest = currScore
currIn = i
tup = a[0],a[currIn]
a[currIn],a[0] = tup
print(*a)
```
| 98,742 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Anu has created her own function f: f(x, y) = (x | y) - y where | denotes the [bitwise OR operation](https://en.wikipedia.org/wiki/Bitwise_operation#OR). For example, f(11, 6) = (11|6) - 6 = 15 - 6 = 9. It can be proved that for any nonnegative numbers x and y value of f(x, y) is also nonnegative.
She would like to research more about this function and has created multiple problems for herself. But she isn't able to solve all of them and needs your help. Here is one of these problems.
A value of an array [a_1, a_2, ..., a_n] is defined as f(f(... f(f(a_1, a_2), a_3), ... a_{n-1}), a_n) (see notes). You are given an array with not necessarily distinct elements. How should you reorder its elements so that the value of the array is maximal possible?
Input
The first line contains a single integer n (1 ≤ n ≤ 10^5).
The second line contains n integers a_1, a_2, …, a_n (0 ≤ a_i ≤ 10^9). Elements of the array are not guaranteed to be different.
Output
Output n integers, the reordering of the array with maximum value. If there are multiple answers, print any.
Examples
Input
4
4 0 11 6
Output
11 6 4 0
Input
1
13
Output
13
Note
In the first testcase, value of the array [11, 6, 4, 0] is f(f(f(11, 6), 4), 0) = f(f(9, 4), 0) = f(9, 0) = 9.
[11, 4, 0, 6] is also a valid answer.
Tags: brute force, greedy, math
Correct Solution:
```
from math import ceil
def mlt(): return map(int, input().split())
x = int(input())
s = list(mlt())
cur = 1 << 32
fst = -1
while cur:
ct = 0
tm = -1
for n in s:
if n & cur:
ct += 1
tm = n
if ct == 1:
fst = tm
break
cur >>= 1
if (fst != -1):
print(fst, end=' ')
for n in s:
if n != fst:
print(n, end=' ')
```
| 98,743 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Anu has created her own function f: f(x, y) = (x | y) - y where | denotes the [bitwise OR operation](https://en.wikipedia.org/wiki/Bitwise_operation#OR). For example, f(11, 6) = (11|6) - 6 = 15 - 6 = 9. It can be proved that for any nonnegative numbers x and y value of f(x, y) is also nonnegative.
She would like to research more about this function and has created multiple problems for herself. But she isn't able to solve all of them and needs your help. Here is one of these problems.
A value of an array [a_1, a_2, ..., a_n] is defined as f(f(... f(f(a_1, a_2), a_3), ... a_{n-1}), a_n) (see notes). You are given an array with not necessarily distinct elements. How should you reorder its elements so that the value of the array is maximal possible?
Input
The first line contains a single integer n (1 ≤ n ≤ 10^5).
The second line contains n integers a_1, a_2, …, a_n (0 ≤ a_i ≤ 10^9). Elements of the array are not guaranteed to be different.
Output
Output n integers, the reordering of the array with maximum value. If there are multiple answers, print any.
Examples
Input
4
4 0 11 6
Output
11 6 4 0
Input
1
13
Output
13
Note
In the first testcase, value of the array [11, 6, 4, 0] is f(f(f(11, 6), 4), 0) = f(f(9, 4), 0) = f(9, 0) = 9.
[11, 4, 0, 6] is also a valid answer.
Tags: brute force, greedy, math
Correct Solution:
```
n=int(input())
pw = [2**(30-i) for i in range(31)]
def kek(x):
global pw
#x=int(x)
ans=set()
mind=0
for i in range(31):
pwi=pw[i]
if pwi<=x:
x-=pwi
ans.add(pwi)
return ans
ra=list(map(int,input().split()))
a=list(map(kek,ra))
t=dict([[pw[i],0] for i in range(31)])
for ii in a:
for i in ii:
t[i]+=1
q=set()
meme=1
for i in range(30,-1,-1):
if t[pw[i]]>1:
q.add(pw[i])
m,mv=-1,-1
for i in a:
idf=sum(i.difference(q))
if idf>mv:
m,mv=i,idf
m=sum(m)
print(m,end=' ')
nmust=False
ra.pop(ra.index(m))
print(' '.join(map(str,ra)))
```
| 98,744 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Anu has created her own function f: f(x, y) = (x | y) - y where | denotes the [bitwise OR operation](https://en.wikipedia.org/wiki/Bitwise_operation#OR). For example, f(11, 6) = (11|6) - 6 = 15 - 6 = 9. It can be proved that for any nonnegative numbers x and y value of f(x, y) is also nonnegative.
She would like to research more about this function and has created multiple problems for herself. But she isn't able to solve all of them and needs your help. Here is one of these problems.
A value of an array [a_1, a_2, ..., a_n] is defined as f(f(... f(f(a_1, a_2), a_3), ... a_{n-1}), a_n) (see notes). You are given an array with not necessarily distinct elements. How should you reorder its elements so that the value of the array is maximal possible?
Input
The first line contains a single integer n (1 ≤ n ≤ 10^5).
The second line contains n integers a_1, a_2, …, a_n (0 ≤ a_i ≤ 10^9). Elements of the array are not guaranteed to be different.
Output
Output n integers, the reordering of the array with maximum value. If there are multiple answers, print any.
Examples
Input
4
4 0 11 6
Output
11 6 4 0
Input
1
13
Output
13
Note
In the first testcase, value of the array [11, 6, 4, 0] is f(f(f(11, 6), 4), 0) = f(f(9, 4), 0) = f(9, 0) = 9.
[11, 4, 0, 6] is also a valid answer.
Tags: brute force, greedy, math
Correct Solution:
```
n=int(input())
a=list(map(int,input().split()))
ans=[]
for i in range(32,-1,-1):
flag=-1
badflag=0
for j in range(n):
if a[j]&1<<i:
if flag==-1:
flag=j
else:
badflag=1
if badflag==1:
break
if flag!=-1 and badflag==0:
ans.append(str(a[flag]))
for j in range(n):
if j!=flag:
ans.append(str(a[j]))
break
if len(ans)==0:
for i in range(n):
ans.append(str(a[i]))
print(' '.join(ans))
```
| 98,745 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Anu has created her own function f: f(x, y) = (x | y) - y where | denotes the [bitwise OR operation](https://en.wikipedia.org/wiki/Bitwise_operation#OR). For example, f(11, 6) = (11|6) - 6 = 15 - 6 = 9. It can be proved that for any nonnegative numbers x and y value of f(x, y) is also nonnegative.
She would like to research more about this function and has created multiple problems for herself. But she isn't able to solve all of them and needs your help. Here is one of these problems.
A value of an array [a_1, a_2, ..., a_n] is defined as f(f(... f(f(a_1, a_2), a_3), ... a_{n-1}), a_n) (see notes). You are given an array with not necessarily distinct elements. How should you reorder its elements so that the value of the array is maximal possible?
Input
The first line contains a single integer n (1 ≤ n ≤ 10^5).
The second line contains n integers a_1, a_2, …, a_n (0 ≤ a_i ≤ 10^9). Elements of the array are not guaranteed to be different.
Output
Output n integers, the reordering of the array with maximum value. If there are multiple answers, print any.
Examples
Input
4
4 0 11 6
Output
11 6 4 0
Input
1
13
Output
13
Note
In the first testcase, value of the array [11, 6, 4, 0] is f(f(f(11, 6), 4), 0) = f(f(9, 4), 0) = f(9, 0) = 9.
[11, 4, 0, 6] is also a valid answer.
Tags: brute force, greedy, math
Correct Solution:
```
from sys import stdin
from bisect import bisect_left as bl
from bisect import bisect_right as br
def input():
return stdin.readline()[:-1]
def intput():
return int(input())
def sinput():
return input().split()
def intsput():
return map(int, sinput())
class RangedList:
def __init__(self, start, stop, val=0):
self.shift = 0 - start
self.start = start
self.stop = stop
self.list = [val] * (stop - start)
def __setitem__(self, key, value):
self.list[key + self.shift] = value
def __getitem__(self, key):
return self.list[key + self.shift]
def __repr__(self):
return str(self.list)
def __iter__(self):
return iter(self.list)
# Code
n = intput()
originals = list(intsput())
flips = [~x for x in originals]
forward = [2**100 - 1]
backward = [2 ** 100 - 1]
for i in range(len(flips)):
forward.append(forward[-1] & flips[i])
for i in range(len(flips) - 1, -1, -1):
backward.append(backward[-1] & flips[i])
best = -1
first = None
for i in range(len(originals)):
trial = forward[i] & originals[i] & backward[len(originals) - 1 - i]
if trial > best:
best = trial
first = originals[i]
originals.remove(first)
originals = [first] + originals
print(*originals)
```
| 98,746 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Anu has created her own function f: f(x, y) = (x | y) - y where | denotes the [bitwise OR operation](https://en.wikipedia.org/wiki/Bitwise_operation#OR). For example, f(11, 6) = (11|6) - 6 = 15 - 6 = 9. It can be proved that for any nonnegative numbers x and y value of f(x, y) is also nonnegative.
She would like to research more about this function and has created multiple problems for herself. But she isn't able to solve all of them and needs your help. Here is one of these problems.
A value of an array [a_1, a_2, ..., a_n] is defined as f(f(... f(f(a_1, a_2), a_3), ... a_{n-1}), a_n) (see notes). You are given an array with not necessarily distinct elements. How should you reorder its elements so that the value of the array is maximal possible?
Input
The first line contains a single integer n (1 ≤ n ≤ 10^5).
The second line contains n integers a_1, a_2, …, a_n (0 ≤ a_i ≤ 10^9). Elements of the array are not guaranteed to be different.
Output
Output n integers, the reordering of the array with maximum value. If there are multiple answers, print any.
Examples
Input
4
4 0 11 6
Output
11 6 4 0
Input
1
13
Output
13
Note
In the first testcase, value of the array [11, 6, 4, 0] is f(f(f(11, 6), 4), 0) = f(f(9, 4), 0) = f(9, 0) = 9.
[11, 4, 0, 6] is also a valid answer.
Tags: brute force, greedy, math
Correct Solution:
```
"""
Satwik_Tiwari ;) .
20 june , 2020 - Tuesday
"""
#===============================================================================================
#importing some useful libraries.
from __future__ import division, print_function
from fractions import Fraction
import sys
import os
from io import BytesIO, IOBase
import bisect
from heapq import *
from math import *
from collections import deque
from collections import Counter as counter # Counter(list) return a dict with {key: count}
from itertools import combinations as comb # if a = [1,2,3] then print(list(comb(a,2))) -----> [(1, 2), (1, 3), (2, 3)]
from itertools import permutations as permutate
from bisect import bisect_left as bl
#If the element is already present in the list,
# the left most position where element has to be inserted is returned.
from bisect import bisect_right as br
from bisect import bisect
#If the element is already present in the list,
# the right most position where element has to be inserted is returned
#==============================================================================================
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")
def print(*args, **kwargs):
"""Prints the values to a stream, or to sys.stdout by default."""
sep, file = kwargs.pop("sep", " "), kwargs.pop("file", sys.stdout)
at_start = True
for x in args:
if not at_start:
file.write(sep)
file.write(str(x))
at_start = False
file.write(kwargs.pop("end", "\n"))
if kwargs.pop("flush", False):
file.flush()
if sys.version_info[0] < 3:
sys.stdin, sys.stdout = FastIO(sys.stdin), FastIO(sys.stdout)
else:
sys.stdin, sys.stdout = IOWrapper(sys.stdin), IOWrapper(sys.stdout)
# inp = lambda: sys.stdin.readline().rstrip("\r\n")
#===============================================================================================
#some shortcuts
mod = 1000000007
def inp(): return sys.stdin.readline().rstrip("\r\n") #for fast input
def out(var): sys.stdout.write(str(var)) #for fast output, always take string
def lis(): return list(map(int, inp().split()))
def stringlis(): return list(map(str, inp().split()))
def sep(): return map(int, inp().split())
def strsep(): return map(str, inp().split())
def graph(vertex): return [[] for i in range(0,vertex+1)]
def zerolist(n): return [0]*n
def nextline(): out("\n") #as stdout.write always print sring.
def testcase(t):
for p in range(t):
solve()
def printlist(a) :
for p in range(0,len(a)):
out(str(a[p]) + ' ')
def lcm(a,b): return (a*b)//gcd(a,b)
def power(a,b):
ans = 1
while(b>0):
if(b%2==1):
ans*=a
a*=a
b//=2
return ans
def ncr(n,r): return factorial(n)//(factorial(r)*factorial(max(n-r,1)))
def isPrime(n) : # Check Prime Number or not
if (n <= 1) : return False
if (n <= 3) : return True
if (n % 2 == 0 or n % 3 == 0) : return False
i = 5
while(i * i <= n) :
if (n % i == 0 or n % (i + 2) == 0) :
return False
i = i + 6
return True
#===============================================================================================
# code here ;))
def bs(a,l,h,x):
while(l<h):
# print(l,h)
mid = (l+h)//2
if(a[mid] == x):
return mid
if(a[mid] < x):
l = mid+1
else:
h = mid
return l
def sieve(a): #O(n loglogn) nearly linear
#all odd mark 1
for i in range(3,((10**6)+1),2):
a[i] = 1
#marking multiples of i form i*i 0. they are nt prime
for i in range(3,((10**6)+1),2):
for j in range(i*i,((10**6)+1),i):
a[j] = 0
a[2] = 1 #special left case
return (a)
def solve():
n = int(inp())
a = lis()
s = '1'*32
if(n==1):
print(a[0])
return
l = []
for i in range(0,n):
if(i==0):
l.append(~a[i])
continue
l.append(l[i-1]&(~a[i]))
r = [0]*(n)
for i in range(n-1,-1,-1):
if(i==n-1):
r[i] = (~a[i])
continue
r[i] = r[i+1] & (~a[i])
ans = -1
ind = -1
for i in range(0,n):
if(i==0):
if(ans < a[i]&(r[i+1])):
ind = i
ans = max(ans,a[i]&(r[i+1]))
continue
if(i==n-1):
if(ans < a[i]&l[i-1]):
ind = i
ans = max(ans,a[i]&l[i-1])
continue
if(ans < l[i-1]&a[i]&r[i+1]):
ind = i
ans =max(ans,l[i-1]&a[i]&r[i+1])
# print(ind)
print(*([a[ind]] + a[:ind] + a[ind+1:]))
testcase(1)
# testcase(int(inp()))
```
| 98,747 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Anu has created her own function f: f(x, y) = (x | y) - y where | denotes the [bitwise OR operation](https://en.wikipedia.org/wiki/Bitwise_operation#OR). For example, f(11, 6) = (11|6) - 6 = 15 - 6 = 9. It can be proved that for any nonnegative numbers x and y value of f(x, y) is also nonnegative.
She would like to research more about this function and has created multiple problems for herself. But she isn't able to solve all of them and needs your help. Here is one of these problems.
A value of an array [a_1, a_2, ..., a_n] is defined as f(f(... f(f(a_1, a_2), a_3), ... a_{n-1}), a_n) (see notes). You are given an array with not necessarily distinct elements. How should you reorder its elements so that the value of the array is maximal possible?
Input
The first line contains a single integer n (1 ≤ n ≤ 10^5).
The second line contains n integers a_1, a_2, …, a_n (0 ≤ a_i ≤ 10^9). Elements of the array are not guaranteed to be different.
Output
Output n integers, the reordering of the array with maximum value. If there are multiple answers, print any.
Examples
Input
4
4 0 11 6
Output
11 6 4 0
Input
1
13
Output
13
Note
In the first testcase, value of the array [11, 6, 4, 0] is f(f(f(11, 6), 4), 0) = f(f(9, 4), 0) = f(9, 0) = 9.
[11, 4, 0, 6] is also a valid answer.
Tags: brute force, greedy, math
Correct Solution:
```
n = int(input())
s = list(map(int, input().split()))
for i in range(30,-1,-1):
if sum(1 for x in s if x&(1<<i)) == 1:
s.sort(key = lambda x: -(x & (1<<i)))
break
print(*s)
```
| 98,748 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Anu has created her own function f: f(x, y) = (x | y) - y where | denotes the [bitwise OR operation](https://en.wikipedia.org/wiki/Bitwise_operation#OR). For example, f(11, 6) = (11|6) - 6 = 15 - 6 = 9. It can be proved that for any nonnegative numbers x and y value of f(x, y) is also nonnegative.
She would like to research more about this function and has created multiple problems for herself. But she isn't able to solve all of them and needs your help. Here is one of these problems.
A value of an array [a_1, a_2, ..., a_n] is defined as f(f(... f(f(a_1, a_2), a_3), ... a_{n-1}), a_n) (see notes). You are given an array with not necessarily distinct elements. How should you reorder its elements so that the value of the array is maximal possible?
Input
The first line contains a single integer n (1 ≤ n ≤ 10^5).
The second line contains n integers a_1, a_2, …, a_n (0 ≤ a_i ≤ 10^9). Elements of the array are not guaranteed to be different.
Output
Output n integers, the reordering of the array with maximum value. If there are multiple answers, print any.
Examples
Input
4
4 0 11 6
Output
11 6 4 0
Input
1
13
Output
13
Note
In the first testcase, value of the array [11, 6, 4, 0] is f(f(f(11, 6), 4), 0) = f(f(9, 4), 0) = f(9, 0) = 9.
[11, 4, 0, 6] is also a valid answer.
Tags: brute force, greedy, math
Correct Solution:
```
from math import log,ceil
def bitnot(n):
if n == 0:
return (1 << 31) - 1
return (1 << 31) - 1 - n
#print(bitnot(4))
n = int(input())
l = [int(i) for i in input().split()]
f = bitnot(l[0])
prefix = []
for i in l:
f &= bitnot(i)
prefix.append(f)
f = bitnot(l[-1])
sufix = []
for i in l[::-1]:
f &= bitnot(i)
sufix.append(f)
#print(l)
#print(prefix)
#print(sufix)
m = [-1,-1]
for i in range(n):
first = l[i]
p = s = 2**31 - 1
if i > 0:
p = prefix[i-1]
if i < n-1:
s = sufix[n-i-2]
#print(p,s)
r = (p & s)
#print('ands:', r)
ans = first & r
#print('ans:', first, ans)
if ans > m[0]:
m[0] = ans
m[1] = i
l[m[1]],l[0] = l[0], l[m[1]]
print(*l)
```
| 98,749 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Anu has created her own function f: f(x, y) = (x | y) - y where | denotes the [bitwise OR operation](https://en.wikipedia.org/wiki/Bitwise_operation#OR). For example, f(11, 6) = (11|6) - 6 = 15 - 6 = 9. It can be proved that for any nonnegative numbers x and y value of f(x, y) is also nonnegative.
She would like to research more about this function and has created multiple problems for herself. But she isn't able to solve all of them and needs your help. Here is one of these problems.
A value of an array [a_1, a_2, ..., a_n] is defined as f(f(... f(f(a_1, a_2), a_3), ... a_{n-1}), a_n) (see notes). You are given an array with not necessarily distinct elements. How should you reorder its elements so that the value of the array is maximal possible?
Input
The first line contains a single integer n (1 ≤ n ≤ 10^5).
The second line contains n integers a_1, a_2, …, a_n (0 ≤ a_i ≤ 10^9). Elements of the array are not guaranteed to be different.
Output
Output n integers, the reordering of the array with maximum value. If there are multiple answers, print any.
Examples
Input
4
4 0 11 6
Output
11 6 4 0
Input
1
13
Output
13
Note
In the first testcase, value of the array [11, 6, 4, 0] is f(f(f(11, 6), 4), 0) = f(f(9, 4), 0) = f(9, 0) = 9.
[11, 4, 0, 6] is also a valid answer.
Submitted Solution:
```
R = lambda: list(map(int, input().split()))
n = int(input())
a = R()
first = 0
for i in range(30, -1, -1):
cnt = 0
for j in range(n):
if a[j] & 1 << i:
cnt += 1
first = j
if cnt == 1:
break
print(a[first], *(a[:first]), *(a[first + 1:]))
```
Yes
| 98,750 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Anu has created her own function f: f(x, y) = (x | y) - y where | denotes the [bitwise OR operation](https://en.wikipedia.org/wiki/Bitwise_operation#OR). For example, f(11, 6) = (11|6) - 6 = 15 - 6 = 9. It can be proved that for any nonnegative numbers x and y value of f(x, y) is also nonnegative.
She would like to research more about this function and has created multiple problems for herself. But she isn't able to solve all of them and needs your help. Here is one of these problems.
A value of an array [a_1, a_2, ..., a_n] is defined as f(f(... f(f(a_1, a_2), a_3), ... a_{n-1}), a_n) (see notes). You are given an array with not necessarily distinct elements. How should you reorder its elements so that the value of the array is maximal possible?
Input
The first line contains a single integer n (1 ≤ n ≤ 10^5).
The second line contains n integers a_1, a_2, …, a_n (0 ≤ a_i ≤ 10^9). Elements of the array are not guaranteed to be different.
Output
Output n integers, the reordering of the array with maximum value. If there are multiple answers, print any.
Examples
Input
4
4 0 11 6
Output
11 6 4 0
Input
1
13
Output
13
Note
In the first testcase, value of the array [11, 6, 4, 0] is f(f(f(11, 6), 4), 0) = f(f(9, 4), 0) = f(9, 0) = 9.
[11, 4, 0, 6] is also a valid answer.
Submitted Solution:
```
n = int(input())
A = list(map(int,input().split()))
B = [[0] * 33 for i in range(n)]
C = [0] * 33
for i in range(n):
t = A[i]
j = 0
while t > 0:
B[i][j] += t%2
C[j] += B[i][j]
t//=2
j += 1
M2 = [1]
for i in range(40):
M2.append(M2[-1]*2)
S = [0] * n
for i in range(n):
for j in range(33):
if B[i][j] == 1:
if C[j] == 1:
S[i] += M2[j]
ind = S.index(max(S))
ANS = [A[ind]]
for i in range(n):
if i != ind:
ANS.append(A[i])
print(" ".join([str(i) for i in ANS]))
```
Yes
| 98,751 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Anu has created her own function f: f(x, y) = (x | y) - y where | denotes the [bitwise OR operation](https://en.wikipedia.org/wiki/Bitwise_operation#OR). For example, f(11, 6) = (11|6) - 6 = 15 - 6 = 9. It can be proved that for any nonnegative numbers x and y value of f(x, y) is also nonnegative.
She would like to research more about this function and has created multiple problems for herself. But she isn't able to solve all of them and needs your help. Here is one of these problems.
A value of an array [a_1, a_2, ..., a_n] is defined as f(f(... f(f(a_1, a_2), a_3), ... a_{n-1}), a_n) (see notes). You are given an array with not necessarily distinct elements. How should you reorder its elements so that the value of the array is maximal possible?
Input
The first line contains a single integer n (1 ≤ n ≤ 10^5).
The second line contains n integers a_1, a_2, …, a_n (0 ≤ a_i ≤ 10^9). Elements of the array are not guaranteed to be different.
Output
Output n integers, the reordering of the array with maximum value. If there are multiple answers, print any.
Examples
Input
4
4 0 11 6
Output
11 6 4 0
Input
1
13
Output
13
Note
In the first testcase, value of the array [11, 6, 4, 0] is f(f(f(11, 6), 4), 0) = f(f(9, 4), 0) = f(9, 0) = 9.
[11, 4, 0, 6] is also a valid answer.
Submitted Solution:
```
# import sys
n = int(input())
a = [int(c) for c in input().split()]
only_1 = (1 << 40) - 1
left = [only_1]
right = [only_1]
L = only_1
for i in range(n - 1):
L = L & ~a[i]
left.append(L)
R = only_1
for i in range(n - 1):
R = R & ~a[n - 1 - i]
# right.insert(0, R)
right.append(R)
# print(left, right)
res = 0
res_i = 0
for i in range(n):
r = a[i] & left[i] & right[n - 1 - i]
if r > res:
res_i = i
res = r
b = [a[res_i]] + [a[j] for j in range(n) if j != res_i]
# print('done', file=sys.stderr)
print(*b)
```
Yes
| 98,752 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Anu has created her own function f: f(x, y) = (x | y) - y where | denotes the [bitwise OR operation](https://en.wikipedia.org/wiki/Bitwise_operation#OR). For example, f(11, 6) = (11|6) - 6 = 15 - 6 = 9. It can be proved that for any nonnegative numbers x and y value of f(x, y) is also nonnegative.
She would like to research more about this function and has created multiple problems for herself. But she isn't able to solve all of them and needs your help. Here is one of these problems.
A value of an array [a_1, a_2, ..., a_n] is defined as f(f(... f(f(a_1, a_2), a_3), ... a_{n-1}), a_n) (see notes). You are given an array with not necessarily distinct elements. How should you reorder its elements so that the value of the array is maximal possible?
Input
The first line contains a single integer n (1 ≤ n ≤ 10^5).
The second line contains n integers a_1, a_2, …, a_n (0 ≤ a_i ≤ 10^9). Elements of the array are not guaranteed to be different.
Output
Output n integers, the reordering of the array with maximum value. If there are multiple answers, print any.
Examples
Input
4
4 0 11 6
Output
11 6 4 0
Input
1
13
Output
13
Note
In the first testcase, value of the array [11, 6, 4, 0] is f(f(f(11, 6), 4), 0) = f(f(9, 4), 0) = f(9, 0) = 9.
[11, 4, 0, 6] is also a valid answer.
Submitted Solution:
```
import sys
input = sys.stdin.readline
N = int(input())
A = list(map(int, input().split()))
if N == 1:
ans = A
else:
dp1 = [0]*N
bit = 0
for i, a in enumerate(A):
bit |= a
dp1[i] = bit
dp2 = [0]*N
bit = 0
for i in reversed(range(N)):
bit |= A[i]
dp2[i] = bit
score = -1
ind = -1
for i in range(N):
if i == 0:
tmp = dp2[1]
elif i == N-1:
tmp = dp1[N-2]
else:
tmp = dp1[i-1]|dp2[i+1]
if (A[i]|tmp)-tmp > score:
score = (A[i]|tmp)-tmp
ind = i
ans = [A[ind]]
for i, a in enumerate(A):
if i != ind:
ans.append(a)
print(*ans, sep=" ")
```
Yes
| 98,753 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Anu has created her own function f: f(x, y) = (x | y) - y where | denotes the [bitwise OR operation](https://en.wikipedia.org/wiki/Bitwise_operation#OR). For example, f(11, 6) = (11|6) - 6 = 15 - 6 = 9. It can be proved that for any nonnegative numbers x and y value of f(x, y) is also nonnegative.
She would like to research more about this function and has created multiple problems for herself. But she isn't able to solve all of them and needs your help. Here is one of these problems.
A value of an array [a_1, a_2, ..., a_n] is defined as f(f(... f(f(a_1, a_2), a_3), ... a_{n-1}), a_n) (see notes). You are given an array with not necessarily distinct elements. How should you reorder its elements so that the value of the array is maximal possible?
Input
The first line contains a single integer n (1 ≤ n ≤ 10^5).
The second line contains n integers a_1, a_2, …, a_n (0 ≤ a_i ≤ 10^9). Elements of the array are not guaranteed to be different.
Output
Output n integers, the reordering of the array with maximum value. If there are multiple answers, print any.
Examples
Input
4
4 0 11 6
Output
11 6 4 0
Input
1
13
Output
13
Note
In the first testcase, value of the array [11, 6, 4, 0] is f(f(f(11, 6), 4), 0) = f(f(9, 4), 0) = f(9, 0) = 9.
[11, 4, 0, 6] is also a valid answer.
Submitted Solution:
```
from sys import stdin
input=stdin.buffer.readline
n=int(input())
arr=[int(x) for x in input().split()]
arr.sort(reverse=True)
print(*arr)
```
No
| 98,754 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Anu has created her own function f: f(x, y) = (x | y) - y where | denotes the [bitwise OR operation](https://en.wikipedia.org/wiki/Bitwise_operation#OR). For example, f(11, 6) = (11|6) - 6 = 15 - 6 = 9. It can be proved that for any nonnegative numbers x and y value of f(x, y) is also nonnegative.
She would like to research more about this function and has created multiple problems for herself. But she isn't able to solve all of them and needs your help. Here is one of these problems.
A value of an array [a_1, a_2, ..., a_n] is defined as f(f(... f(f(a_1, a_2), a_3), ... a_{n-1}), a_n) (see notes). You are given an array with not necessarily distinct elements. How should you reorder its elements so that the value of the array is maximal possible?
Input
The first line contains a single integer n (1 ≤ n ≤ 10^5).
The second line contains n integers a_1, a_2, …, a_n (0 ≤ a_i ≤ 10^9). Elements of the array are not guaranteed to be different.
Output
Output n integers, the reordering of the array with maximum value. If there are multiple answers, print any.
Examples
Input
4
4 0 11 6
Output
11 6 4 0
Input
1
13
Output
13
Note
In the first testcase, value of the array [11, 6, 4, 0] is f(f(f(11, 6), 4), 0) = f(f(9, 4), 0) = f(9, 0) = 9.
[11, 4, 0, 6] is also a valid answer.
Submitted Solution:
```
n = int(input())
arr = [int(x) for x in input().split()]
for x in arr:
print(x, end=' ')
```
No
| 98,755 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Anu has created her own function f: f(x, y) = (x | y) - y where | denotes the [bitwise OR operation](https://en.wikipedia.org/wiki/Bitwise_operation#OR). For example, f(11, 6) = (11|6) - 6 = 15 - 6 = 9. It can be proved that for any nonnegative numbers x and y value of f(x, y) is also nonnegative.
She would like to research more about this function and has created multiple problems for herself. But she isn't able to solve all of them and needs your help. Here is one of these problems.
A value of an array [a_1, a_2, ..., a_n] is defined as f(f(... f(f(a_1, a_2), a_3), ... a_{n-1}), a_n) (see notes). You are given an array with not necessarily distinct elements. How should you reorder its elements so that the value of the array is maximal possible?
Input
The first line contains a single integer n (1 ≤ n ≤ 10^5).
The second line contains n integers a_1, a_2, …, a_n (0 ≤ a_i ≤ 10^9). Elements of the array are not guaranteed to be different.
Output
Output n integers, the reordering of the array with maximum value. If there are multiple answers, print any.
Examples
Input
4
4 0 11 6
Output
11 6 4 0
Input
1
13
Output
13
Note
In the first testcase, value of the array [11, 6, 4, 0] is f(f(f(11, 6), 4), 0) = f(f(9, 4), 0) = f(9, 0) = 9.
[11, 4, 0, 6] is also a valid answer.
Submitted Solution:
```
t=1
while t>0:
t-=1
n=int(input())
a=[int(x) for x in input().split()]
d={}
l=[0 for i in range(70)]
for i in range(n):
u=bin(a[i])[2:]
#print(a[i],"0"*(40-len(u))+u)
for k in range(len(u)):
if u[k]=='1':
l[len(u)-k-1]+=1
if a[i] in d:
d[a[i]]+=1
else:
d[a[i]]=1
a.sort(reverse=True)
maxi=-1
for k in range(len(u)-1,-1,-1):
for i in range(n):
u=bin(a[i])[2:]
u="0"*(70-len(u))+bin(a[i])[2:]
if u[k]=='1' and l[len(u)-k-1]==1:
maxi=a[i]
break
if maxi!=-1:
break
if maxi==-1:
maxi=a[0]
a.remove(maxi)
print(maxi,*a)
```
No
| 98,756 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Anu has created her own function f: f(x, y) = (x | y) - y where | denotes the [bitwise OR operation](https://en.wikipedia.org/wiki/Bitwise_operation#OR). For example, f(11, 6) = (11|6) - 6 = 15 - 6 = 9. It can be proved that for any nonnegative numbers x and y value of f(x, y) is also nonnegative.
She would like to research more about this function and has created multiple problems for herself. But she isn't able to solve all of them and needs your help. Here is one of these problems.
A value of an array [a_1, a_2, ..., a_n] is defined as f(f(... f(f(a_1, a_2), a_3), ... a_{n-1}), a_n) (see notes). You are given an array with not necessarily distinct elements. How should you reorder its elements so that the value of the array is maximal possible?
Input
The first line contains a single integer n (1 ≤ n ≤ 10^5).
The second line contains n integers a_1, a_2, …, a_n (0 ≤ a_i ≤ 10^9). Elements of the array are not guaranteed to be different.
Output
Output n integers, the reordering of the array with maximum value. If there are multiple answers, print any.
Examples
Input
4
4 0 11 6
Output
11 6 4 0
Input
1
13
Output
13
Note
In the first testcase, value of the array [11, 6, 4, 0] is f(f(f(11, 6), 4), 0) = f(f(9, 4), 0) = f(9, 0) = 9.
[11, 4, 0, 6] is also a valid answer.
Submitted Solution:
```
n = int(input())
l = list(map(int, input().split()))
m = [[0, 0] for _ in range(n)]
for i in range(n):
bin_str = format(l[i], 'b')
p = 0
for j in range(len(bin_str)):
if bin_str[j] == '1':
p += 1
m[i][0] = l[i]
m[i][1] = p
m_ = sorted(m, key=lambda x:(x[0],x[1]), reverse=True)
#print(m_)
l_ = [str(c[0]) for c in m_]
print(' '.join(l_))
```
No
| 98,757 |
Provide tags and a correct Python 3 solution for this coding contest problem.
The next lecture in a high school requires two topics to be discussed. The i-th topic is interesting by a_i units for the teacher and by b_i units for the students.
The pair of topics i and j (i < j) is called good if a_i + a_j > b_i + b_j (i.e. it is more interesting for the teacher).
Your task is to find the number of good pairs of topics.
Input
The first line of the input contains one integer n (2 ≤ n ≤ 2 ⋅ 10^5) — the number of topics.
The second line of the input contains n integers a_1, a_2, ..., a_n (1 ≤ a_i ≤ 10^9), where a_i is the interestingness of the i-th topic for the teacher.
The third line of the input contains n integers b_1, b_2, ..., b_n (1 ≤ b_i ≤ 10^9), where b_i is the interestingness of the i-th topic for the students.
Output
Print one integer — the number of good pairs of topic.
Examples
Input
5
4 8 2 6 2
4 5 4 1 3
Output
7
Input
4
1 3 2 4
1 3 2 4
Output
0
Tags: binary search, data structures, sortings, two pointers
Correct Solution:
```
from sys import *
n=int(stdin.readline())
a=[int(x) for x in stdin.readline().split()]
b=[int(x) for x in stdin.readline().split()]
count=0
c=[]
for i in range(n):
c.append(a[i]-b[i])
c=sorted(c)
i=0
j=n-1
while(i<j):
if(c[i]+c[j]>0):
count+=j-i
j=j-1
else:
i=i+1
print(count)
```
| 98,758 |
Provide tags and a correct Python 3 solution for this coding contest problem.
The next lecture in a high school requires two topics to be discussed. The i-th topic is interesting by a_i units for the teacher and by b_i units for the students.
The pair of topics i and j (i < j) is called good if a_i + a_j > b_i + b_j (i.e. it is more interesting for the teacher).
Your task is to find the number of good pairs of topics.
Input
The first line of the input contains one integer n (2 ≤ n ≤ 2 ⋅ 10^5) — the number of topics.
The second line of the input contains n integers a_1, a_2, ..., a_n (1 ≤ a_i ≤ 10^9), where a_i is the interestingness of the i-th topic for the teacher.
The third line of the input contains n integers b_1, b_2, ..., b_n (1 ≤ b_i ≤ 10^9), where b_i is the interestingness of the i-th topic for the students.
Output
Print one integer — the number of good pairs of topic.
Examples
Input
5
4 8 2 6 2
4 5 4 1 3
Output
7
Input
4
1 3 2 4
1 3 2 4
Output
0
Tags: binary search, data structures, sortings, two pointers
Correct Solution:
```
n = int(input())
a = list(map(int,input().split()))
b = list(map(int,input().split()))
c = [a[i]-b[i] for i in range(n)]
c.sort()
ind = n - 1
wyn = 0
for i in range(n):
while True:
if ind > i and c[i] + c[ind] > 0:
ind -= 1
else:
break
if ind <= i:
ind = min(n-1,i)
wyn += (n-1-ind)
print(wyn)
```
| 98,759 |
Provide tags and a correct Python 3 solution for this coding contest problem.
The next lecture in a high school requires two topics to be discussed. The i-th topic is interesting by a_i units for the teacher and by b_i units for the students.
The pair of topics i and j (i < j) is called good if a_i + a_j > b_i + b_j (i.e. it is more interesting for the teacher).
Your task is to find the number of good pairs of topics.
Input
The first line of the input contains one integer n (2 ≤ n ≤ 2 ⋅ 10^5) — the number of topics.
The second line of the input contains n integers a_1, a_2, ..., a_n (1 ≤ a_i ≤ 10^9), where a_i is the interestingness of the i-th topic for the teacher.
The third line of the input contains n integers b_1, b_2, ..., b_n (1 ≤ b_i ≤ 10^9), where b_i is the interestingness of the i-th topic for the students.
Output
Print one integer — the number of good pairs of topic.
Examples
Input
5
4 8 2 6 2
4 5 4 1 3
Output
7
Input
4
1 3 2 4
1 3 2 4
Output
0
Tags: binary search, data structures, sortings, two pointers
Correct Solution:
```
import sys
input = lambda: sys.stdin.readline().rstrip()
n = int(input())
a = list(map(int, input().split()))
b = list(map(int, input().split()))
part = []
for i in range(n):
part.append(a[i] - b[i])
part.sort()
ans = 0
for i in range(n):
if part[i] > 0:
ans += n - i - 1
else:
L = 0
R = n
while L < R - 1:
mid = (L + R) // 2
if part[mid] > abs(part[i]):
R = mid
else:
L = mid
ans += n - R
print(ans)
```
| 98,760 |
Provide tags and a correct Python 3 solution for this coding contest problem.
The next lecture in a high school requires two topics to be discussed. The i-th topic is interesting by a_i units for the teacher and by b_i units for the students.
The pair of topics i and j (i < j) is called good if a_i + a_j > b_i + b_j (i.e. it is more interesting for the teacher).
Your task is to find the number of good pairs of topics.
Input
The first line of the input contains one integer n (2 ≤ n ≤ 2 ⋅ 10^5) — the number of topics.
The second line of the input contains n integers a_1, a_2, ..., a_n (1 ≤ a_i ≤ 10^9), where a_i is the interestingness of the i-th topic for the teacher.
The third line of the input contains n integers b_1, b_2, ..., b_n (1 ≤ b_i ≤ 10^9), where b_i is the interestingness of the i-th topic for the students.
Output
Print one integer — the number of good pairs of topic.
Examples
Input
5
4 8 2 6 2
4 5 4 1 3
Output
7
Input
4
1 3 2 4
1 3 2 4
Output
0
Tags: binary search, data structures, sortings, two pointers
Correct Solution:
```
import sys
input = sys.stdin.readline
from bisect import bisect_left
n = int(input())
x = [*map(int, input().split())]
y = [xi - yi for xi, yi in zip(x, map(int, input().split()))]
#print(y)
y.sort()
ans = 0
for i in range(n):
k = y[i]
a = bisect_left(y, -k+1)
ans += n-a
print((ans - len([i for i in y if i > 0]))// 2)
```
| 98,761 |
Provide tags and a correct Python 3 solution for this coding contest problem.
The next lecture in a high school requires two topics to be discussed. The i-th topic is interesting by a_i units for the teacher and by b_i units for the students.
The pair of topics i and j (i < j) is called good if a_i + a_j > b_i + b_j (i.e. it is more interesting for the teacher).
Your task is to find the number of good pairs of topics.
Input
The first line of the input contains one integer n (2 ≤ n ≤ 2 ⋅ 10^5) — the number of topics.
The second line of the input contains n integers a_1, a_2, ..., a_n (1 ≤ a_i ≤ 10^9), where a_i is the interestingness of the i-th topic for the teacher.
The third line of the input contains n integers b_1, b_2, ..., b_n (1 ≤ b_i ≤ 10^9), where b_i is the interestingness of the i-th topic for the students.
Output
Print one integer — the number of good pairs of topic.
Examples
Input
5
4 8 2 6 2
4 5 4 1 3
Output
7
Input
4
1 3 2 4
1 3 2 4
Output
0
Tags: binary search, data structures, sortings, two pointers
Correct Solution:
```
n=int(input())
ans=i=0
j=n-1
diff=[]
p=[]
j=n-1
list1=list(map(int,input().split()))
list2=list(map(int,input().split()))
zip_object = zip(list1,list2)
for list1_i, list2_i in zip_object:
diff.append(list1_i-list2_i)
#print(diff)
diff.sort()
#print(diff)
while(i<j):
if diff[i]+diff[j]>0:
ans+=j-i
j=j-1
else:
i+=1
print(ans)
```
| 98,762 |
Provide tags and a correct Python 3 solution for this coding contest problem.
The next lecture in a high school requires two topics to be discussed. The i-th topic is interesting by a_i units for the teacher and by b_i units for the students.
The pair of topics i and j (i < j) is called good if a_i + a_j > b_i + b_j (i.e. it is more interesting for the teacher).
Your task is to find the number of good pairs of topics.
Input
The first line of the input contains one integer n (2 ≤ n ≤ 2 ⋅ 10^5) — the number of topics.
The second line of the input contains n integers a_1, a_2, ..., a_n (1 ≤ a_i ≤ 10^9), where a_i is the interestingness of the i-th topic for the teacher.
The third line of the input contains n integers b_1, b_2, ..., b_n (1 ≤ b_i ≤ 10^9), where b_i is the interestingness of the i-th topic for the students.
Output
Print one integer — the number of good pairs of topic.
Examples
Input
5
4 8 2 6 2
4 5 4 1 3
Output
7
Input
4
1 3 2 4
1 3 2 4
Output
0
Tags: binary search, data structures, sortings, two pointers
Correct Solution:
```
import collections
import bisect
def solve(n, teacherInterests, studentInterests):
diffs = []
for t, s in zip(teacherInterests, studentInterests):
diffs.append(t-s)
diffs.sort()
ans = 0
# print(diffs)
for i, difference in enumerate(diffs):
if difference <= 0:
continue
pos = bisect.bisect_left(diffs, -difference + 1)
ans += i - pos
return ans
n = int(input().strip())
teacherInterests = list(map(int, input().strip().split()))
studentInterests = list(map(int, input().strip().split()))
print(solve(n, teacherInterests, studentInterests))
```
| 98,763 |
Provide tags and a correct Python 3 solution for this coding contest problem.
The next lecture in a high school requires two topics to be discussed. The i-th topic is interesting by a_i units for the teacher and by b_i units for the students.
The pair of topics i and j (i < j) is called good if a_i + a_j > b_i + b_j (i.e. it is more interesting for the teacher).
Your task is to find the number of good pairs of topics.
Input
The first line of the input contains one integer n (2 ≤ n ≤ 2 ⋅ 10^5) — the number of topics.
The second line of the input contains n integers a_1, a_2, ..., a_n (1 ≤ a_i ≤ 10^9), where a_i is the interestingness of the i-th topic for the teacher.
The third line of the input contains n integers b_1, b_2, ..., b_n (1 ≤ b_i ≤ 10^9), where b_i is the interestingness of the i-th topic for the students.
Output
Print one integer — the number of good pairs of topic.
Examples
Input
5
4 8 2 6 2
4 5 4 1 3
Output
7
Input
4
1 3 2 4
1 3 2 4
Output
0
Tags: binary search, data structures, sortings, two pointers
Correct Solution:
```
def binarySearch(A,start,end,x):
if start>end:
return start
mid=(start+end)//2
if A[mid]==x:
return mid
elif A[mid]>x:
return binarySearch(A,start,mid-1,x)
else:
return binarySearch(A,mid+1,end,x)
n=int(input())
A=[int(i) for i in input().split()]
B=[int(i) for i in input().split()]
pos=[]
neg=[]
for i in range(n):
tmp=A[i]-B[i]
if tmp>0:
pos.append(tmp)
else:
neg.append(tmp)
pos.sort()
neg.sort()
toplam=0
for i in range(len(neg)):
tmp=-neg[i]+1
s=binarySearch(pos,0,len(pos)-1,tmp)
if s<len(pos) and pos[s]==tmp:
while(pos[s]==tmp and s>=0):
s-=1
s+=1
toplam+=len(pos)-s
toplam+=(len(pos)*(len(pos)-1))//2
print(toplam)
```
| 98,764 |
Provide tags and a correct Python 3 solution for this coding contest problem.
The next lecture in a high school requires two topics to be discussed. The i-th topic is interesting by a_i units for the teacher and by b_i units for the students.
The pair of topics i and j (i < j) is called good if a_i + a_j > b_i + b_j (i.e. it is more interesting for the teacher).
Your task is to find the number of good pairs of topics.
Input
The first line of the input contains one integer n (2 ≤ n ≤ 2 ⋅ 10^5) — the number of topics.
The second line of the input contains n integers a_1, a_2, ..., a_n (1 ≤ a_i ≤ 10^9), where a_i is the interestingness of the i-th topic for the teacher.
The third line of the input contains n integers b_1, b_2, ..., b_n (1 ≤ b_i ≤ 10^9), where b_i is the interestingness of the i-th topic for the students.
Output
Print one integer — the number of good pairs of topic.
Examples
Input
5
4 8 2 6 2
4 5 4 1 3
Output
7
Input
4
1 3 2 4
1 3 2 4
Output
0
Tags: binary search, data structures, sortings, two pointers
Correct Solution:
```
def binary_search(arr, st, ed, comp):
ans = -1
while st <= ed:
mid = (st + ed) // 2
if arr[mid] + comp > 0:
ans = mid
ed = mid-1
else:
st = mid+1
return ans
n = int(input())
a = input().split()
b = input().split()
nums = []
for i in range(n):
a[i] = int(a[i])
b[i] = int(b[i])
nums.append(a[i] - b[i])
nums.sort()
num_pairs = 0
for i in range(n):
large_start_idx = binary_search(nums, i+1, n-1, nums[i])
if large_start_idx == -1:
continue
num_pairs += n-large_start_idx
print(num_pairs)
```
| 98,765 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
The next lecture in a high school requires two topics to be discussed. The i-th topic is interesting by a_i units for the teacher and by b_i units for the students.
The pair of topics i and j (i < j) is called good if a_i + a_j > b_i + b_j (i.e. it is more interesting for the teacher).
Your task is to find the number of good pairs of topics.
Input
The first line of the input contains one integer n (2 ≤ n ≤ 2 ⋅ 10^5) — the number of topics.
The second line of the input contains n integers a_1, a_2, ..., a_n (1 ≤ a_i ≤ 10^9), where a_i is the interestingness of the i-th topic for the teacher.
The third line of the input contains n integers b_1, b_2, ..., b_n (1 ≤ b_i ≤ 10^9), where b_i is the interestingness of the i-th topic for the students.
Output
Print one integer — the number of good pairs of topic.
Examples
Input
5
4 8 2 6 2
4 5 4 1 3
Output
7
Input
4
1 3 2 4
1 3 2 4
Output
0
Submitted Solution:
```
import sys
#sys.stdin = open("input.txt")
#T = int(input())
def trova(a,b,x):
if x>=a:
return a
if x <= b:
while x==C[b]:
b = b-1
return b
m = (a+b)//2
if x == C[m]:
while x == C[m]:
m = m-1
return m
if a == b:
while C[a] == x:
a = a-1
return a
if x < C[m]:
trova(m,b,x)
return
if x > C[m]:
trova(a,m,x)
return
T = 1
t = 0
while t<T:
N = int(input())
A = list(map(int,input().split()))
B = list(map(int,input().split()))
n = 0
C = []
while n<N:
C.append(A[n]-B[n])
n +=1
C.sort(reverse = True)
n = 0
out = 0
#print (C)
inizio = 0
fine = N-1
while inizio<fine:
if C[inizio]+C[fine] > 0:
out += fine - inizio
inizio +=1
else:
fine -=1
print (out)
t +=1
```
Yes
| 98,766 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
The next lecture in a high school requires two topics to be discussed. The i-th topic is interesting by a_i units for the teacher and by b_i units for the students.
The pair of topics i and j (i < j) is called good if a_i + a_j > b_i + b_j (i.e. it is more interesting for the teacher).
Your task is to find the number of good pairs of topics.
Input
The first line of the input contains one integer n (2 ≤ n ≤ 2 ⋅ 10^5) — the number of topics.
The second line of the input contains n integers a_1, a_2, ..., a_n (1 ≤ a_i ≤ 10^9), where a_i is the interestingness of the i-th topic for the teacher.
The third line of the input contains n integers b_1, b_2, ..., b_n (1 ≤ b_i ≤ 10^9), where b_i is the interestingness of the i-th topic for the students.
Output
Print one integer — the number of good pairs of topic.
Examples
Input
5
4 8 2 6 2
4 5 4 1 3
Output
7
Input
4
1 3 2 4
1 3 2 4
Output
0
Submitted Solution:
```
from bisect import bisect_right as left
n=int(input())
a=list(map(int,input().split()))
b=list(map(int,input().split()))
m=[]
ans=0
for i in range(n):
m.append(a[i]-b[i])
m.sort()
p,ne=[],[]
ans=0
for i in range(n):
if m[i]>0:
ans-=1
ans+=n-left(m,-m[i])
print(ans//2)
```
Yes
| 98,767 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
The next lecture in a high school requires two topics to be discussed. The i-th topic is interesting by a_i units for the teacher and by b_i units for the students.
The pair of topics i and j (i < j) is called good if a_i + a_j > b_i + b_j (i.e. it is more interesting for the teacher).
Your task is to find the number of good pairs of topics.
Input
The first line of the input contains one integer n (2 ≤ n ≤ 2 ⋅ 10^5) — the number of topics.
The second line of the input contains n integers a_1, a_2, ..., a_n (1 ≤ a_i ≤ 10^9), where a_i is the interestingness of the i-th topic for the teacher.
The third line of the input contains n integers b_1, b_2, ..., b_n (1 ≤ b_i ≤ 10^9), where b_i is the interestingness of the i-th topic for the students.
Output
Print one integer — the number of good pairs of topic.
Examples
Input
5
4 8 2 6 2
4 5 4 1 3
Output
7
Input
4
1 3 2 4
1 3 2 4
Output
0
Submitted Solution:
```
import sys
# from math import ceil,floor,tan
import bisect
RI = lambda : [int(x) for x in sys.stdin.readline().split()]
ri = lambda : sys.stdin.readline().strip()
n = int(ri())
a = RI()
b= RI()
c = [a[i]-b[i] for i in range(n)]
c.sort()
i=0
while i < len(c) and c[i] < 0 :
i+=1
ans = 0
for i in range(i,n):
pos = bisect.bisect_left(c,1-c[i])
if pos < i:
ans+=(i-pos)
print(ans)
```
Yes
| 98,768 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
The next lecture in a high school requires two topics to be discussed. The i-th topic is interesting by a_i units for the teacher and by b_i units for the students.
The pair of topics i and j (i < j) is called good if a_i + a_j > b_i + b_j (i.e. it is more interesting for the teacher).
Your task is to find the number of good pairs of topics.
Input
The first line of the input contains one integer n (2 ≤ n ≤ 2 ⋅ 10^5) — the number of topics.
The second line of the input contains n integers a_1, a_2, ..., a_n (1 ≤ a_i ≤ 10^9), where a_i is the interestingness of the i-th topic for the teacher.
The third line of the input contains n integers b_1, b_2, ..., b_n (1 ≤ b_i ≤ 10^9), where b_i is the interestingness of the i-th topic for the students.
Output
Print one integer — the number of good pairs of topic.
Examples
Input
5
4 8 2 6 2
4 5 4 1 3
Output
7
Input
4
1 3 2 4
1 3 2 4
Output
0
Submitted Solution:
```
n = int(input())
l = list(map(int, input().split()))
m = list(map(int, input().split()))
for i in range(n):
l[i] -= m[i]
l.sort()
i = 0
j = n - 1
count = 0
while j > i:
if l[j] + l[i] > 0:
count += j - i
j -= 1
else:
i += 1
print(count)
```
Yes
| 98,769 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
The next lecture in a high school requires two topics to be discussed. The i-th topic is interesting by a_i units for the teacher and by b_i units for the students.
The pair of topics i and j (i < j) is called good if a_i + a_j > b_i + b_j (i.e. it is more interesting for the teacher).
Your task is to find the number of good pairs of topics.
Input
The first line of the input contains one integer n (2 ≤ n ≤ 2 ⋅ 10^5) — the number of topics.
The second line of the input contains n integers a_1, a_2, ..., a_n (1 ≤ a_i ≤ 10^9), where a_i is the interestingness of the i-th topic for the teacher.
The third line of the input contains n integers b_1, b_2, ..., b_n (1 ≤ b_i ≤ 10^9), where b_i is the interestingness of the i-th topic for the students.
Output
Print one integer — the number of good pairs of topic.
Examples
Input
5
4 8 2 6 2
4 5 4 1 3
Output
7
Input
4
1 3 2 4
1 3 2 4
Output
0
Submitted Solution:
```
from bisect import *
qtd = int(input())
dif = sorted([int(a) - int(b) for a, b in zip([int(x) for x in input().split()],[int(x) for x in input().split()])])
#todas as combinacoes dos positivos:
totalpos = qtd
for el in dif:
if el <= 0:
totalpos -= 1
else:
break
output = int(totalpos*(totalpos-1)/2)
i = 0
while(dif[i] < 0):
maisDir = bisect_left(dif, -dif[i], i, qtd)-1
output += qtd - maisDir
i += 1
print(output)
```
No
| 98,770 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
The next lecture in a high school requires two topics to be discussed. The i-th topic is interesting by a_i units for the teacher and by b_i units for the students.
The pair of topics i and j (i < j) is called good if a_i + a_j > b_i + b_j (i.e. it is more interesting for the teacher).
Your task is to find the number of good pairs of topics.
Input
The first line of the input contains one integer n (2 ≤ n ≤ 2 ⋅ 10^5) — the number of topics.
The second line of the input contains n integers a_1, a_2, ..., a_n (1 ≤ a_i ≤ 10^9), where a_i is the interestingness of the i-th topic for the teacher.
The third line of the input contains n integers b_1, b_2, ..., b_n (1 ≤ b_i ≤ 10^9), where b_i is the interestingness of the i-th topic for the students.
Output
Print one integer — the number of good pairs of topic.
Examples
Input
5
4 8 2 6 2
4 5 4 1 3
Output
7
Input
4
1 3 2 4
1 3 2 4
Output
0
Submitted Solution:
```
from bisect import bisect_left as bisect
n=int(input())
a=list(map(int,input().split()))
b=list(map(int,input().split()))
c=[a[i]-b[i] for i in range(n)]
c.sort()
cu=0
for i in c:
x=1-i
z=bisect(c,x)
if x<0:
cu+=(n-z)-1
else:
cu+=(n-z)
print(cu//2)
```
No
| 98,771 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
The next lecture in a high school requires two topics to be discussed. The i-th topic is interesting by a_i units for the teacher and by b_i units for the students.
The pair of topics i and j (i < j) is called good if a_i + a_j > b_i + b_j (i.e. it is more interesting for the teacher).
Your task is to find the number of good pairs of topics.
Input
The first line of the input contains one integer n (2 ≤ n ≤ 2 ⋅ 10^5) — the number of topics.
The second line of the input contains n integers a_1, a_2, ..., a_n (1 ≤ a_i ≤ 10^9), where a_i is the interestingness of the i-th topic for the teacher.
The third line of the input contains n integers b_1, b_2, ..., b_n (1 ≤ b_i ≤ 10^9), where b_i is the interestingness of the i-th topic for the students.
Output
Print one integer — the number of good pairs of topic.
Examples
Input
5
4 8 2 6 2
4 5 4 1 3
Output
7
Input
4
1 3 2 4
1 3 2 4
Output
0
Submitted Solution:
```
all_data = input()
n = int(all_data)
print(n)
x1 = input()
x2 = input()
l1 = [int(x) for x in x1.split(' ')]
l2 = [int(x) for x in x2.split(' ')]
print(l1, l2)
cnt = 0
for i in range(n):
for j in range(i + 1, n):
if l1[i] + l1[j] > l2[i] + l2[j]:
cnt += 1
print(cnt)
```
No
| 98,772 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
The next lecture in a high school requires two topics to be discussed. The i-th topic is interesting by a_i units for the teacher and by b_i units for the students.
The pair of topics i and j (i < j) is called good if a_i + a_j > b_i + b_j (i.e. it is more interesting for the teacher).
Your task is to find the number of good pairs of topics.
Input
The first line of the input contains one integer n (2 ≤ n ≤ 2 ⋅ 10^5) — the number of topics.
The second line of the input contains n integers a_1, a_2, ..., a_n (1 ≤ a_i ≤ 10^9), where a_i is the interestingness of the i-th topic for the teacher.
The third line of the input contains n integers b_1, b_2, ..., b_n (1 ≤ b_i ≤ 10^9), where b_i is the interestingness of the i-th topic for the students.
Output
Print one integer — the number of good pairs of topic.
Examples
Input
5
4 8 2 6 2
4 5 4 1 3
Output
7
Input
4
1 3 2 4
1 3 2 4
Output
0
Submitted Solution:
```
# limit for array size
N = 100001;
# Max size of tree
tree = [0] * (2 * N);
# function to build the tree
def build(arr) :
# insert leaf nodes in tree
for i in range(n) :
tree[n + i] = arr[i];
# build the tree by calculating parents
for i in range(n - 1, 0, -1) :
tree[i] = tree[i << 1] + tree[i << 1 | 1];
# function to update a tree node
def updateTreeNode(p, value) :
# set value at position p
tree[p + n] = value;
p = p + n;
# move upward and update parents
i = p;
while i > 1 :
tree[i >> 1] = tree[i] + tree[i ^ 1];
i >>= 1;
# function to get sum on interval [l, r)
def query(l, r) :
res = 0;
# loop to find the sum in the range
l += n;
r += n;
while l < r :
if (l & 1) :
res += tree[l];
l += 1
if (r & 1) :
r -= 1;
res += tree[r];
l >>= 1;
r >>= 1
return res;
from collections import defaultdict
import bisect
#a,b = map(int,input().strip().split())
n = int(input().strip())
a = [int(i) for i in input().strip().split()]
b = [int(i) for i in input().strip().split()]
minus = [(a[i] - b[i],i) for i in range(n)]
minus.sort()
order = [i[1] for i in minus]
minus = [i[0] for i in minus]
total = 0
temp = [0 for i in range(n)]
build(temp)
#print(minus)
for i in range(n):
result = a[i] - b[i]
ans = bisect.bisect_right(minus,result)
#print(i,result,ans)
total += n - ans
if ans < n:
total -= query(ans + 1,n + 1)
updateTreeNode(order[i], 1)
#print(tree[:10])
print(total)
```
No
| 98,773 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Recall that the sequence b is a a subsequence of the sequence a if b can be derived from a by removing zero or more elements without changing the order of the remaining elements. For example, if a=[1, 2, 1, 3, 1, 2, 1], then possible subsequences are: [1, 1, 1, 1], [3] and [1, 2, 1, 3, 1, 2, 1], but not [3, 2, 3] and [1, 1, 1, 1, 2].
You are given a sequence a consisting of n positive and negative elements (there is no zeros in the sequence).
Your task is to choose maximum by size (length) alternating subsequence of the given sequence (i.e. the sign of each next element is the opposite from the sign of the current element, like positive-negative-positive and so on or negative-positive-negative and so on). Among all such subsequences, you have to choose one which has the maximum sum of elements.
In other words, if the maximum length of alternating subsequence is k then your task is to find the maximum sum of elements of some alternating subsequence of length k.
You have to answer t independent test cases.
Input
The first line of the input contains one integer t (1 ≤ t ≤ 10^4) — the number of test cases. Then t test cases follow.
The first line of the test case contains one integer n (1 ≤ n ≤ 2 ⋅ 10^5) — the number of elements in a. The second line of the test case contains n integers a_1, a_2, ..., a_n (-10^9 ≤ a_i ≤ 10^9, a_i ≠ 0), where a_i is the i-th element of a.
It is guaranteed that the sum of n over all test cases does not exceed 2 ⋅ 10^5 (∑ n ≤ 2 ⋅ 10^5).
Output
For each test case, print the answer — the maximum sum of the maximum by size (length) alternating subsequence of a.
Example
Input
4
5
1 2 3 -1 -2
4
-1 -2 -1 -3
10
-2 8 3 8 -4 -15 5 -2 -3 1
6
1 -1000000000 1 -1000000000 1 -1000000000
Output
2
-1
6
-2999999997
Note
In the first test case of the example, one of the possible answers is [1, 2, \underline{3}, \underline{-1}, -2].
In the second test case of the example, one of the possible answers is [-1, -2, \underline{-1}, -3].
In the third test case of the example, one of the possible answers is [\underline{-2}, 8, 3, \underline{8}, \underline{-4}, -15, \underline{5}, \underline{-2}, -3, \underline{1}].
In the fourth test case of the example, one of the possible answers is [\underline{1}, \underline{-1000000000}, \underline{1}, \underline{-1000000000}, \underline{1}, \underline{-1000000000}].
Tags: dp, greedy, two pointers
Correct Solution:
```
def fun(n,l):
prev=l[0]
sum=[]
for i in range(1,n):
if prev>0 and l[i]<0:
sum.append(prev)
prev=l[i]
elif prev<0 and l[i]>0:
sum.append(prev)
prev = l[i]
elif prev<l[i]:
prev=l[i]
if i==n-1:
sum.append(prev)
suma=0
for i in sum:
suma+=i
print(suma)
for T in range(int(input())):
n=int(input())
l=list(map(int,input().split()))
if n>1:
fun(n,l)
else:
print(l[0])
```
| 98,774 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Recall that the sequence b is a a subsequence of the sequence a if b can be derived from a by removing zero or more elements without changing the order of the remaining elements. For example, if a=[1, 2, 1, 3, 1, 2, 1], then possible subsequences are: [1, 1, 1, 1], [3] and [1, 2, 1, 3, 1, 2, 1], but not [3, 2, 3] and [1, 1, 1, 1, 2].
You are given a sequence a consisting of n positive and negative elements (there is no zeros in the sequence).
Your task is to choose maximum by size (length) alternating subsequence of the given sequence (i.e. the sign of each next element is the opposite from the sign of the current element, like positive-negative-positive and so on or negative-positive-negative and so on). Among all such subsequences, you have to choose one which has the maximum sum of elements.
In other words, if the maximum length of alternating subsequence is k then your task is to find the maximum sum of elements of some alternating subsequence of length k.
You have to answer t independent test cases.
Input
The first line of the input contains one integer t (1 ≤ t ≤ 10^4) — the number of test cases. Then t test cases follow.
The first line of the test case contains one integer n (1 ≤ n ≤ 2 ⋅ 10^5) — the number of elements in a. The second line of the test case contains n integers a_1, a_2, ..., a_n (-10^9 ≤ a_i ≤ 10^9, a_i ≠ 0), where a_i is the i-th element of a.
It is guaranteed that the sum of n over all test cases does not exceed 2 ⋅ 10^5 (∑ n ≤ 2 ⋅ 10^5).
Output
For each test case, print the answer — the maximum sum of the maximum by size (length) alternating subsequence of a.
Example
Input
4
5
1 2 3 -1 -2
4
-1 -2 -1 -3
10
-2 8 3 8 -4 -15 5 -2 -3 1
6
1 -1000000000 1 -1000000000 1 -1000000000
Output
2
-1
6
-2999999997
Note
In the first test case of the example, one of the possible answers is [1, 2, \underline{3}, \underline{-1}, -2].
In the second test case of the example, one of the possible answers is [-1, -2, \underline{-1}, -3].
In the third test case of the example, one of the possible answers is [\underline{-2}, 8, 3, \underline{8}, \underline{-4}, -15, \underline{5}, \underline{-2}, -3, \underline{1}].
In the fourth test case of the example, one of the possible answers is [\underline{1}, \underline{-1000000000}, \underline{1}, \underline{-1000000000}, \underline{1}, \underline{-1000000000}].
Tags: dp, greedy, two pointers
Correct Solution:
```
# import sys
# sys.stdin = open('input.txt', 'r')
# sys.stdout = open('output.txt', 'w')
for _ in range(int(input())):
n=int(input())
count_even=0
count_odd=0
li=[int(x) for x in input().split()]
ans=0
i=0
while(True):
if(i==n):
break
if(li[i]>0):
var=0
while(li[i]>0 and i<n):
var=max(var,li[i])
i+=1
if(i==n):
break
ans+=var
else:
var=-1e18
if(i==n):
break
while(li[i]<0 and i<n):
var=max(var,li[i])
i+=1
if(i==n):
break
ans+=var
if(i==n):
break
print(ans)
```
| 98,775 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Recall that the sequence b is a a subsequence of the sequence a if b can be derived from a by removing zero or more elements without changing the order of the remaining elements. For example, if a=[1, 2, 1, 3, 1, 2, 1], then possible subsequences are: [1, 1, 1, 1], [3] and [1, 2, 1, 3, 1, 2, 1], but not [3, 2, 3] and [1, 1, 1, 1, 2].
You are given a sequence a consisting of n positive and negative elements (there is no zeros in the sequence).
Your task is to choose maximum by size (length) alternating subsequence of the given sequence (i.e. the sign of each next element is the opposite from the sign of the current element, like positive-negative-positive and so on or negative-positive-negative and so on). Among all such subsequences, you have to choose one which has the maximum sum of elements.
In other words, if the maximum length of alternating subsequence is k then your task is to find the maximum sum of elements of some alternating subsequence of length k.
You have to answer t independent test cases.
Input
The first line of the input contains one integer t (1 ≤ t ≤ 10^4) — the number of test cases. Then t test cases follow.
The first line of the test case contains one integer n (1 ≤ n ≤ 2 ⋅ 10^5) — the number of elements in a. The second line of the test case contains n integers a_1, a_2, ..., a_n (-10^9 ≤ a_i ≤ 10^9, a_i ≠ 0), where a_i is the i-th element of a.
It is guaranteed that the sum of n over all test cases does not exceed 2 ⋅ 10^5 (∑ n ≤ 2 ⋅ 10^5).
Output
For each test case, print the answer — the maximum sum of the maximum by size (length) alternating subsequence of a.
Example
Input
4
5
1 2 3 -1 -2
4
-1 -2 -1 -3
10
-2 8 3 8 -4 -15 5 -2 -3 1
6
1 -1000000000 1 -1000000000 1 -1000000000
Output
2
-1
6
-2999999997
Note
In the first test case of the example, one of the possible answers is [1, 2, \underline{3}, \underline{-1}, -2].
In the second test case of the example, one of the possible answers is [-1, -2, \underline{-1}, -3].
In the third test case of the example, one of the possible answers is [\underline{-2}, 8, 3, \underline{8}, \underline{-4}, -15, \underline{5}, \underline{-2}, -3, \underline{1}].
In the fourth test case of the example, one of the possible answers is [\underline{1}, \underline{-1000000000}, \underline{1}, \underline{-1000000000}, \underline{1}, \underline{-1000000000}].
Tags: dp, greedy, two pointers
Correct Solution:
```
for _ in range(int(input())):
n = int(input())
data = list(map(int, input().split()))
result = 0
if data[0] > 0:
sign = 1
else:
sign = -1
array = []
for x in data:
if sign == 1 and x > 0:
array.append(x)
if sign == 1 and x < 0:
sign = -1
result += max(array)
array = [x]
if sign == -1 and x < 0:
array.append(x)
if sign == -1 and x > 0:
sign = 1
result += max(array)
array = [x]
result += max(array)
print(result)
```
| 98,776 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Recall that the sequence b is a a subsequence of the sequence a if b can be derived from a by removing zero or more elements without changing the order of the remaining elements. For example, if a=[1, 2, 1, 3, 1, 2, 1], then possible subsequences are: [1, 1, 1, 1], [3] and [1, 2, 1, 3, 1, 2, 1], but not [3, 2, 3] and [1, 1, 1, 1, 2].
You are given a sequence a consisting of n positive and negative elements (there is no zeros in the sequence).
Your task is to choose maximum by size (length) alternating subsequence of the given sequence (i.e. the sign of each next element is the opposite from the sign of the current element, like positive-negative-positive and so on or negative-positive-negative and so on). Among all such subsequences, you have to choose one which has the maximum sum of elements.
In other words, if the maximum length of alternating subsequence is k then your task is to find the maximum sum of elements of some alternating subsequence of length k.
You have to answer t independent test cases.
Input
The first line of the input contains one integer t (1 ≤ t ≤ 10^4) — the number of test cases. Then t test cases follow.
The first line of the test case contains one integer n (1 ≤ n ≤ 2 ⋅ 10^5) — the number of elements in a. The second line of the test case contains n integers a_1, a_2, ..., a_n (-10^9 ≤ a_i ≤ 10^9, a_i ≠ 0), where a_i is the i-th element of a.
It is guaranteed that the sum of n over all test cases does not exceed 2 ⋅ 10^5 (∑ n ≤ 2 ⋅ 10^5).
Output
For each test case, print the answer — the maximum sum of the maximum by size (length) alternating subsequence of a.
Example
Input
4
5
1 2 3 -1 -2
4
-1 -2 -1 -3
10
-2 8 3 8 -4 -15 5 -2 -3 1
6
1 -1000000000 1 -1000000000 1 -1000000000
Output
2
-1
6
-2999999997
Note
In the first test case of the example, one of the possible answers is [1, 2, \underline{3}, \underline{-1}, -2].
In the second test case of the example, one of the possible answers is [-1, -2, \underline{-1}, -3].
In the third test case of the example, one of the possible answers is [\underline{-2}, 8, 3, \underline{8}, \underline{-4}, -15, \underline{5}, \underline{-2}, -3, \underline{1}].
In the fourth test case of the example, one of the possible answers is [\underline{1}, \underline{-1000000000}, \underline{1}, \underline{-1000000000}, \underline{1}, \underline{-1000000000}].
Tags: dp, greedy, two pointers
Correct Solution:
```
import math
import sys
from collections import defaultdict
from collections import Counter
from collections import deque
import bisect
input = iter(sys.stdin.buffer.read().decode().splitlines()).__next__
ilele = lambda: map(int,input().split())
alele = lambda: list(map(int, input().split()))
def list2d(a, b, c): return [[c] * b for i in range(a)]
def list3d(a, b, c, d): return [[[d] * c for j in range(b)] for i in range(a)]
for _ in range(int(input())):
N = int(input())
A = alele()
i = 0;B = [];temp = [];pos = -1
while i<len(A):
if len(temp) == 0:
if A[i] < 0:
pos = 0
temp.append(A[i])
else:
pos = 1
temp.append(A[i])
else:
if pos == 1:
if A[i] > 0:
temp.append(A[i])
else:
pos = 0
B.append(max(temp))
temp = []
temp.append(A[i])
else:
if A[i] < 0:
temp.append(A[i])
else:
pos = 1
B.append(max(temp))
temp = []
temp.append(A[i])
i+=1
if len(temp) != 0:
if temp[0]<0:
B.append(max(temp))
else:
B.append(max(temp))
#print(B)
print(sum(B))
```
| 98,777 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Recall that the sequence b is a a subsequence of the sequence a if b can be derived from a by removing zero or more elements without changing the order of the remaining elements. For example, if a=[1, 2, 1, 3, 1, 2, 1], then possible subsequences are: [1, 1, 1, 1], [3] and [1, 2, 1, 3, 1, 2, 1], but not [3, 2, 3] and [1, 1, 1, 1, 2].
You are given a sequence a consisting of n positive and negative elements (there is no zeros in the sequence).
Your task is to choose maximum by size (length) alternating subsequence of the given sequence (i.e. the sign of each next element is the opposite from the sign of the current element, like positive-negative-positive and so on or negative-positive-negative and so on). Among all such subsequences, you have to choose one which has the maximum sum of elements.
In other words, if the maximum length of alternating subsequence is k then your task is to find the maximum sum of elements of some alternating subsequence of length k.
You have to answer t independent test cases.
Input
The first line of the input contains one integer t (1 ≤ t ≤ 10^4) — the number of test cases. Then t test cases follow.
The first line of the test case contains one integer n (1 ≤ n ≤ 2 ⋅ 10^5) — the number of elements in a. The second line of the test case contains n integers a_1, a_2, ..., a_n (-10^9 ≤ a_i ≤ 10^9, a_i ≠ 0), where a_i is the i-th element of a.
It is guaranteed that the sum of n over all test cases does not exceed 2 ⋅ 10^5 (∑ n ≤ 2 ⋅ 10^5).
Output
For each test case, print the answer — the maximum sum of the maximum by size (length) alternating subsequence of a.
Example
Input
4
5
1 2 3 -1 -2
4
-1 -2 -1 -3
10
-2 8 3 8 -4 -15 5 -2 -3 1
6
1 -1000000000 1 -1000000000 1 -1000000000
Output
2
-1
6
-2999999997
Note
In the first test case of the example, one of the possible answers is [1, 2, \underline{3}, \underline{-1}, -2].
In the second test case of the example, one of the possible answers is [-1, -2, \underline{-1}, -3].
In the third test case of the example, one of the possible answers is [\underline{-2}, 8, 3, \underline{8}, \underline{-4}, -15, \underline{5}, \underline{-2}, -3, \underline{1}].
In the fourth test case of the example, one of the possible answers is [\underline{1}, \underline{-1000000000}, \underline{1}, \underline{-1000000000}, \underline{1}, \underline{-1000000000}].
Tags: dp, greedy, two pointers
Correct Solution:
```
for _ in range(int(input())):
n=int(input())
ar=list(map(int,input().split()))
if(ar[0]>0):
ty='p'
else:
ty='n'
li=[]
ans=0
for i in range(n):
if(ar[i]>0):
if(ty=='p'):
li.append(ar[i])
else:
ans+=max(li)
li=[ar[i]]
ty='p'
if(ar[i]<0):
if(ty=='n'):
li.append(ar[i])
else:
ans+=max(li)
li=[ar[i]]
ty='n'
ans+=max(li)
print(ans)
```
| 98,778 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Recall that the sequence b is a a subsequence of the sequence a if b can be derived from a by removing zero or more elements without changing the order of the remaining elements. For example, if a=[1, 2, 1, 3, 1, 2, 1], then possible subsequences are: [1, 1, 1, 1], [3] and [1, 2, 1, 3, 1, 2, 1], but not [3, 2, 3] and [1, 1, 1, 1, 2].
You are given a sequence a consisting of n positive and negative elements (there is no zeros in the sequence).
Your task is to choose maximum by size (length) alternating subsequence of the given sequence (i.e. the sign of each next element is the opposite from the sign of the current element, like positive-negative-positive and so on or negative-positive-negative and so on). Among all such subsequences, you have to choose one which has the maximum sum of elements.
In other words, if the maximum length of alternating subsequence is k then your task is to find the maximum sum of elements of some alternating subsequence of length k.
You have to answer t independent test cases.
Input
The first line of the input contains one integer t (1 ≤ t ≤ 10^4) — the number of test cases. Then t test cases follow.
The first line of the test case contains one integer n (1 ≤ n ≤ 2 ⋅ 10^5) — the number of elements in a. The second line of the test case contains n integers a_1, a_2, ..., a_n (-10^9 ≤ a_i ≤ 10^9, a_i ≠ 0), where a_i is the i-th element of a.
It is guaranteed that the sum of n over all test cases does not exceed 2 ⋅ 10^5 (∑ n ≤ 2 ⋅ 10^5).
Output
For each test case, print the answer — the maximum sum of the maximum by size (length) alternating subsequence of a.
Example
Input
4
5
1 2 3 -1 -2
4
-1 -2 -1 -3
10
-2 8 3 8 -4 -15 5 -2 -3 1
6
1 -1000000000 1 -1000000000 1 -1000000000
Output
2
-1
6
-2999999997
Note
In the first test case of the example, one of the possible answers is [1, 2, \underline{3}, \underline{-1}, -2].
In the second test case of the example, one of the possible answers is [-1, -2, \underline{-1}, -3].
In the third test case of the example, one of the possible answers is [\underline{-2}, 8, 3, \underline{8}, \underline{-4}, -15, \underline{5}, \underline{-2}, -3, \underline{1}].
In the fourth test case of the example, one of the possible answers is [\underline{1}, \underline{-1000000000}, \underline{1}, \underline{-1000000000}, \underline{1}, \underline{-1000000000}].
Tags: dp, greedy, two pointers
Correct Solution:
```
for _ in range(int(input())):
n = int(input())
lst = list(map(int,input().split()))
i = 0
ans = 0
while(i<n):
if(lst[i]>0):
j = i+1
maxPos = lst[i]
while(j<n and lst[j]>0):
maxPos = max(maxPos,lst[j])
j+=1
ans+=maxPos
i = j
else:
j =i+1
maxNeg = lst[i]
while(j<n and lst[j]<0):
maxNeg = max(maxNeg,lst[j])
j+=1
ans+=maxNeg
i = j
print(ans)
```
| 98,779 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Recall that the sequence b is a a subsequence of the sequence a if b can be derived from a by removing zero or more elements without changing the order of the remaining elements. For example, if a=[1, 2, 1, 3, 1, 2, 1], then possible subsequences are: [1, 1, 1, 1], [3] and [1, 2, 1, 3, 1, 2, 1], but not [3, 2, 3] and [1, 1, 1, 1, 2].
You are given a sequence a consisting of n positive and negative elements (there is no zeros in the sequence).
Your task is to choose maximum by size (length) alternating subsequence of the given sequence (i.e. the sign of each next element is the opposite from the sign of the current element, like positive-negative-positive and so on or negative-positive-negative and so on). Among all such subsequences, you have to choose one which has the maximum sum of elements.
In other words, if the maximum length of alternating subsequence is k then your task is to find the maximum sum of elements of some alternating subsequence of length k.
You have to answer t independent test cases.
Input
The first line of the input contains one integer t (1 ≤ t ≤ 10^4) — the number of test cases. Then t test cases follow.
The first line of the test case contains one integer n (1 ≤ n ≤ 2 ⋅ 10^5) — the number of elements in a. The second line of the test case contains n integers a_1, a_2, ..., a_n (-10^9 ≤ a_i ≤ 10^9, a_i ≠ 0), where a_i is the i-th element of a.
It is guaranteed that the sum of n over all test cases does not exceed 2 ⋅ 10^5 (∑ n ≤ 2 ⋅ 10^5).
Output
For each test case, print the answer — the maximum sum of the maximum by size (length) alternating subsequence of a.
Example
Input
4
5
1 2 3 -1 -2
4
-1 -2 -1 -3
10
-2 8 3 8 -4 -15 5 -2 -3 1
6
1 -1000000000 1 -1000000000 1 -1000000000
Output
2
-1
6
-2999999997
Note
In the first test case of the example, one of the possible answers is [1, 2, \underline{3}, \underline{-1}, -2].
In the second test case of the example, one of the possible answers is [-1, -2, \underline{-1}, -3].
In the third test case of the example, one of the possible answers is [\underline{-2}, 8, 3, \underline{8}, \underline{-4}, -15, \underline{5}, \underline{-2}, -3, \underline{1}].
In the fourth test case of the example, one of the possible answers is [\underline{1}, \underline{-1000000000}, \underline{1}, \underline{-1000000000}, \underline{1}, \underline{-1000000000}].
Tags: dp, greedy, two pointers
Correct Solution:
```
for _ in range(int(input())):
m=int(input())
l=list(map(int,input().split()))
q=[]
p=[]
i=0
res=0
while(i<m):
while(i<m and l[i]>0):
q.append(l[i])
i=i+1
#print(q)
while(i<m and l[i]<0):
p.append(l[i])
i+=1
#print(p)
if(len(q)==0):
y=0
else:
y=max(q)
if(len(p)==0):
x=0
else:
x=max(p)
#print(";;;x",x)
#print("////y",y)
res=res+x+y
#print("res",res)
p=[]
q=[]
print(res)
```
| 98,780 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Recall that the sequence b is a a subsequence of the sequence a if b can be derived from a by removing zero or more elements without changing the order of the remaining elements. For example, if a=[1, 2, 1, 3, 1, 2, 1], then possible subsequences are: [1, 1, 1, 1], [3] and [1, 2, 1, 3, 1, 2, 1], but not [3, 2, 3] and [1, 1, 1, 1, 2].
You are given a sequence a consisting of n positive and negative elements (there is no zeros in the sequence).
Your task is to choose maximum by size (length) alternating subsequence of the given sequence (i.e. the sign of each next element is the opposite from the sign of the current element, like positive-negative-positive and so on or negative-positive-negative and so on). Among all such subsequences, you have to choose one which has the maximum sum of elements.
In other words, if the maximum length of alternating subsequence is k then your task is to find the maximum sum of elements of some alternating subsequence of length k.
You have to answer t independent test cases.
Input
The first line of the input contains one integer t (1 ≤ t ≤ 10^4) — the number of test cases. Then t test cases follow.
The first line of the test case contains one integer n (1 ≤ n ≤ 2 ⋅ 10^5) — the number of elements in a. The second line of the test case contains n integers a_1, a_2, ..., a_n (-10^9 ≤ a_i ≤ 10^9, a_i ≠ 0), where a_i is the i-th element of a.
It is guaranteed that the sum of n over all test cases does not exceed 2 ⋅ 10^5 (∑ n ≤ 2 ⋅ 10^5).
Output
For each test case, print the answer — the maximum sum of the maximum by size (length) alternating subsequence of a.
Example
Input
4
5
1 2 3 -1 -2
4
-1 -2 -1 -3
10
-2 8 3 8 -4 -15 5 -2 -3 1
6
1 -1000000000 1 -1000000000 1 -1000000000
Output
2
-1
6
-2999999997
Note
In the first test case of the example, one of the possible answers is [1, 2, \underline{3}, \underline{-1}, -2].
In the second test case of the example, one of the possible answers is [-1, -2, \underline{-1}, -3].
In the third test case of the example, one of the possible answers is [\underline{-2}, 8, 3, \underline{8}, \underline{-4}, -15, \underline{5}, \underline{-2}, -3, \underline{1}].
In the fourth test case of the example, one of the possible answers is [\underline{1}, \underline{-1000000000}, \underline{1}, \underline{-1000000000}, \underline{1}, \underline{-1000000000}].
Tags: dp, greedy, two pointers
Correct Solution:
```
t = int(input())
for _ in range(t):
n = int(input())
a = list(map(int, input().split()))
ans = 0
pos = True if a[0] > 0 else False
mini = a[0]
for i in range(n):
if (a[i] > 0 and pos) or (a[i] < 0 and not pos):
mini = max(mini, a[i])
else:
ans += mini
mini = a[i]
pos = not pos
ans += mini
print(ans)
```
| 98,781 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Recall that the sequence b is a a subsequence of the sequence a if b can be derived from a by removing zero or more elements without changing the order of the remaining elements. For example, if a=[1, 2, 1, 3, 1, 2, 1], then possible subsequences are: [1, 1, 1, 1], [3] and [1, 2, 1, 3, 1, 2, 1], but not [3, 2, 3] and [1, 1, 1, 1, 2].
You are given a sequence a consisting of n positive and negative elements (there is no zeros in the sequence).
Your task is to choose maximum by size (length) alternating subsequence of the given sequence (i.e. the sign of each next element is the opposite from the sign of the current element, like positive-negative-positive and so on or negative-positive-negative and so on). Among all such subsequences, you have to choose one which has the maximum sum of elements.
In other words, if the maximum length of alternating subsequence is k then your task is to find the maximum sum of elements of some alternating subsequence of length k.
You have to answer t independent test cases.
Input
The first line of the input contains one integer t (1 ≤ t ≤ 10^4) — the number of test cases. Then t test cases follow.
The first line of the test case contains one integer n (1 ≤ n ≤ 2 ⋅ 10^5) — the number of elements in a. The second line of the test case contains n integers a_1, a_2, ..., a_n (-10^9 ≤ a_i ≤ 10^9, a_i ≠ 0), where a_i is the i-th element of a.
It is guaranteed that the sum of n over all test cases does not exceed 2 ⋅ 10^5 (∑ n ≤ 2 ⋅ 10^5).
Output
For each test case, print the answer — the maximum sum of the maximum by size (length) alternating subsequence of a.
Example
Input
4
5
1 2 3 -1 -2
4
-1 -2 -1 -3
10
-2 8 3 8 -4 -15 5 -2 -3 1
6
1 -1000000000 1 -1000000000 1 -1000000000
Output
2
-1
6
-2999999997
Note
In the first test case of the example, one of the possible answers is [1, 2, \underline{3}, \underline{-1}, -2].
In the second test case of the example, one of the possible answers is [-1, -2, \underline{-1}, -3].
In the third test case of the example, one of the possible answers is [\underline{-2}, 8, 3, \underline{8}, \underline{-4}, -15, \underline{5}, \underline{-2}, -3, \underline{1}].
In the fourth test case of the example, one of the possible answers is [\underline{1}, \underline{-1000000000}, \underline{1}, \underline{-1000000000}, \underline{1}, \underline{-1000000000}].
Submitted Solution:
```
import math
import sys
input = sys.stdin.readline
def solve(n, arr):
seg = -math.inf
neg = arr[0] < 0
total = 0
for a in arr:
if a < 0 and neg:
seg = max(seg, a)
elif a > 0 and not neg:
seg = max(seg, a)
else:
if (a < 0 and not neg) or (a > 0 and neg):
total += seg
seg = a
neg = a < 0
return total + seg
if __name__ == "__main__":
t = int(input())
for i in range(t):
n = int(input())
arr = list(map(int,input().split()))
print(solve(n, arr))
```
Yes
| 98,782 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Recall that the sequence b is a a subsequence of the sequence a if b can be derived from a by removing zero or more elements without changing the order of the remaining elements. For example, if a=[1, 2, 1, 3, 1, 2, 1], then possible subsequences are: [1, 1, 1, 1], [3] and [1, 2, 1, 3, 1, 2, 1], but not [3, 2, 3] and [1, 1, 1, 1, 2].
You are given a sequence a consisting of n positive and negative elements (there is no zeros in the sequence).
Your task is to choose maximum by size (length) alternating subsequence of the given sequence (i.e. the sign of each next element is the opposite from the sign of the current element, like positive-negative-positive and so on or negative-positive-negative and so on). Among all such subsequences, you have to choose one which has the maximum sum of elements.
In other words, if the maximum length of alternating subsequence is k then your task is to find the maximum sum of elements of some alternating subsequence of length k.
You have to answer t independent test cases.
Input
The first line of the input contains one integer t (1 ≤ t ≤ 10^4) — the number of test cases. Then t test cases follow.
The first line of the test case contains one integer n (1 ≤ n ≤ 2 ⋅ 10^5) — the number of elements in a. The second line of the test case contains n integers a_1, a_2, ..., a_n (-10^9 ≤ a_i ≤ 10^9, a_i ≠ 0), where a_i is the i-th element of a.
It is guaranteed that the sum of n over all test cases does not exceed 2 ⋅ 10^5 (∑ n ≤ 2 ⋅ 10^5).
Output
For each test case, print the answer — the maximum sum of the maximum by size (length) alternating subsequence of a.
Example
Input
4
5
1 2 3 -1 -2
4
-1 -2 -1 -3
10
-2 8 3 8 -4 -15 5 -2 -3 1
6
1 -1000000000 1 -1000000000 1 -1000000000
Output
2
-1
6
-2999999997
Note
In the first test case of the example, one of the possible answers is [1, 2, \underline{3}, \underline{-1}, -2].
In the second test case of the example, one of the possible answers is [-1, -2, \underline{-1}, -3].
In the third test case of the example, one of the possible answers is [\underline{-2}, 8, 3, \underline{8}, \underline{-4}, -15, \underline{5}, \underline{-2}, -3, \underline{1}].
In the fourth test case of the example, one of the possible answers is [\underline{1}, \underline{-1000000000}, \underline{1}, \underline{-1000000000}, \underline{1}, \underline{-1000000000}].
Submitted Solution:
```
t = int(input())
for i in range(t):
n = int(input())
a = list(map(int,input().split()))
if (a[0]>0):
pos = a[0]
flag=True
ans_sum = a[0]
elif (a[0]<0):
neg = a[0]
flag=False
ans_sum = a[0]
for j in range(1,n):
if ((a[j]>0)):
if ((flag==True)):
if ((a[j]>pos)):
ans_sum = ans_sum - pos
pos = a[j]
ans_sum = ans_sum + a[j]
else:
pos = a[j]
ans_sum = ans_sum + a[j]
flag=True
else:
if ((flag==False)):
if ((a[j]>neg)):
ans_sum = ans_sum - neg
neg = a[j]
ans_sum = ans_sum + a[j]
else:
neg = a[j]
ans_sum = ans_sum + a[j]
flag=False
print(ans_sum)
```
Yes
| 98,783 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Recall that the sequence b is a a subsequence of the sequence a if b can be derived from a by removing zero or more elements without changing the order of the remaining elements. For example, if a=[1, 2, 1, 3, 1, 2, 1], then possible subsequences are: [1, 1, 1, 1], [3] and [1, 2, 1, 3, 1, 2, 1], but not [3, 2, 3] and [1, 1, 1, 1, 2].
You are given a sequence a consisting of n positive and negative elements (there is no zeros in the sequence).
Your task is to choose maximum by size (length) alternating subsequence of the given sequence (i.e. the sign of each next element is the opposite from the sign of the current element, like positive-negative-positive and so on or negative-positive-negative and so on). Among all such subsequences, you have to choose one which has the maximum sum of elements.
In other words, if the maximum length of alternating subsequence is k then your task is to find the maximum sum of elements of some alternating subsequence of length k.
You have to answer t independent test cases.
Input
The first line of the input contains one integer t (1 ≤ t ≤ 10^4) — the number of test cases. Then t test cases follow.
The first line of the test case contains one integer n (1 ≤ n ≤ 2 ⋅ 10^5) — the number of elements in a. The second line of the test case contains n integers a_1, a_2, ..., a_n (-10^9 ≤ a_i ≤ 10^9, a_i ≠ 0), where a_i is the i-th element of a.
It is guaranteed that the sum of n over all test cases does not exceed 2 ⋅ 10^5 (∑ n ≤ 2 ⋅ 10^5).
Output
For each test case, print the answer — the maximum sum of the maximum by size (length) alternating subsequence of a.
Example
Input
4
5
1 2 3 -1 -2
4
-1 -2 -1 -3
10
-2 8 3 8 -4 -15 5 -2 -3 1
6
1 -1000000000 1 -1000000000 1 -1000000000
Output
2
-1
6
-2999999997
Note
In the first test case of the example, one of the possible answers is [1, 2, \underline{3}, \underline{-1}, -2].
In the second test case of the example, one of the possible answers is [-1, -2, \underline{-1}, -3].
In the third test case of the example, one of the possible answers is [\underline{-2}, 8, 3, \underline{8}, \underline{-4}, -15, \underline{5}, \underline{-2}, -3, \underline{1}].
In the fourth test case of the example, one of the possible answers is [\underline{1}, \underline{-1000000000}, \underline{1}, \underline{-1000000000}, \underline{1}, \underline{-1000000000}].
Submitted Solution:
```
t= int(input())
for i in range(0,t):
n=int(input())
a=list(map(int,input().split()))
count=0
max=0
max1=0
m=0
s=0
for j in range(0,n):
if(a[j]>0):
count=count+max
max=0
if(s==0):
max1=a[j]
s=1
m=0
if(a[j]>max1):
max1=a[j]
else:
count=count+max1
max1=0
if(m==0):
max=a[j]
m=1
s=0
if(max<a[j]):
max=a[j]
if(a[n-1]>0):
count=count+max1
else:
count=count+max
print(count)
```
Yes
| 98,784 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Recall that the sequence b is a a subsequence of the sequence a if b can be derived from a by removing zero or more elements without changing the order of the remaining elements. For example, if a=[1, 2, 1, 3, 1, 2, 1], then possible subsequences are: [1, 1, 1, 1], [3] and [1, 2, 1, 3, 1, 2, 1], but not [3, 2, 3] and [1, 1, 1, 1, 2].
You are given a sequence a consisting of n positive and negative elements (there is no zeros in the sequence).
Your task is to choose maximum by size (length) alternating subsequence of the given sequence (i.e. the sign of each next element is the opposite from the sign of the current element, like positive-negative-positive and so on or negative-positive-negative and so on). Among all such subsequences, you have to choose one which has the maximum sum of elements.
In other words, if the maximum length of alternating subsequence is k then your task is to find the maximum sum of elements of some alternating subsequence of length k.
You have to answer t independent test cases.
Input
The first line of the input contains one integer t (1 ≤ t ≤ 10^4) — the number of test cases. Then t test cases follow.
The first line of the test case contains one integer n (1 ≤ n ≤ 2 ⋅ 10^5) — the number of elements in a. The second line of the test case contains n integers a_1, a_2, ..., a_n (-10^9 ≤ a_i ≤ 10^9, a_i ≠ 0), where a_i is the i-th element of a.
It is guaranteed that the sum of n over all test cases does not exceed 2 ⋅ 10^5 (∑ n ≤ 2 ⋅ 10^5).
Output
For each test case, print the answer — the maximum sum of the maximum by size (length) alternating subsequence of a.
Example
Input
4
5
1 2 3 -1 -2
4
-1 -2 -1 -3
10
-2 8 3 8 -4 -15 5 -2 -3 1
6
1 -1000000000 1 -1000000000 1 -1000000000
Output
2
-1
6
-2999999997
Note
In the first test case of the example, one of the possible answers is [1, 2, \underline{3}, \underline{-1}, -2].
In the second test case of the example, one of the possible answers is [-1, -2, \underline{-1}, -3].
In the third test case of the example, one of the possible answers is [\underline{-2}, 8, 3, \underline{8}, \underline{-4}, -15, \underline{5}, \underline{-2}, -3, \underline{1}].
In the fourth test case of the example, one of the possible answers is [\underline{1}, \underline{-1000000000}, \underline{1}, \underline{-1000000000}, \underline{1}, \underline{-1000000000}].
Submitted Solution:
```
t = int(input())
while(t>0):
n= int(input())
arr =[int(i) for i in input().split()]
l= 0
r= 0
r= 1
if arr[l]>0:
flag =1
else:
flag= 0
out= []
while(r<n):
if arr[r]>0 and flag == 1:
r+=1
continue
elif arr[r]<0 and flag ==0:
r+=1
continue
elif flag==1:
out.append(max(arr[l:r]))
l= r
flag= 0
elif flag==0:
out.append(max(arr[l:r]))
l= r
flag= 1
r+=1
if flag==1:
out.append(max(arr[l:r]))
l= r
flag= 0
else:
out.append(max(arr[l:r]))
l= r
flag= 1
print(sum(out))
t-=1
```
Yes
| 98,785 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Recall that the sequence b is a a subsequence of the sequence a if b can be derived from a by removing zero or more elements without changing the order of the remaining elements. For example, if a=[1, 2, 1, 3, 1, 2, 1], then possible subsequences are: [1, 1, 1, 1], [3] and [1, 2, 1, 3, 1, 2, 1], but not [3, 2, 3] and [1, 1, 1, 1, 2].
You are given a sequence a consisting of n positive and negative elements (there is no zeros in the sequence).
Your task is to choose maximum by size (length) alternating subsequence of the given sequence (i.e. the sign of each next element is the opposite from the sign of the current element, like positive-negative-positive and so on or negative-positive-negative and so on). Among all such subsequences, you have to choose one which has the maximum sum of elements.
In other words, if the maximum length of alternating subsequence is k then your task is to find the maximum sum of elements of some alternating subsequence of length k.
You have to answer t independent test cases.
Input
The first line of the input contains one integer t (1 ≤ t ≤ 10^4) — the number of test cases. Then t test cases follow.
The first line of the test case contains one integer n (1 ≤ n ≤ 2 ⋅ 10^5) — the number of elements in a. The second line of the test case contains n integers a_1, a_2, ..., a_n (-10^9 ≤ a_i ≤ 10^9, a_i ≠ 0), where a_i is the i-th element of a.
It is guaranteed that the sum of n over all test cases does not exceed 2 ⋅ 10^5 (∑ n ≤ 2 ⋅ 10^5).
Output
For each test case, print the answer — the maximum sum of the maximum by size (length) alternating subsequence of a.
Example
Input
4
5
1 2 3 -1 -2
4
-1 -2 -1 -3
10
-2 8 3 8 -4 -15 5 -2 -3 1
6
1 -1000000000 1 -1000000000 1 -1000000000
Output
2
-1
6
-2999999997
Note
In the first test case of the example, one of the possible answers is [1, 2, \underline{3}, \underline{-1}, -2].
In the second test case of the example, one of the possible answers is [-1, -2, \underline{-1}, -3].
In the third test case of the example, one of the possible answers is [\underline{-2}, 8, 3, \underline{8}, \underline{-4}, -15, \underline{5}, \underline{-2}, -3, \underline{1}].
In the fourth test case of the example, one of the possible answers is [\underline{1}, \underline{-1000000000}, \underline{1}, \underline{-1000000000}, \underline{1}, \underline{-1000000000}].
Submitted Solution:
```
def ans(a):
count = 0
s = ''
temp_l = [[a[0]]]
arr = []
for i in range(1,len(a)):
if (a[i]>0 and a[i-1]<0) or (a[i]<0 and a[i-1]>0):
temp_l[-1].append(a[i])
else:
temp_l.append([a[i]])
print(temp_l)
q = -1
w = [min(a)] #ans
for i in temp_l:
e = len(i)
f = sum(i)
if e>=q:
if f>sum(w):
w = i
q = e
t = sum(w)
return(t)
q = int(input())
for i in range(q):
b = input()
a = input().split()
s = []
for i in a:
s.append(int(i))
print(ans(s))
```
No
| 98,786 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Recall that the sequence b is a a subsequence of the sequence a if b can be derived from a by removing zero or more elements without changing the order of the remaining elements. For example, if a=[1, 2, 1, 3, 1, 2, 1], then possible subsequences are: [1, 1, 1, 1], [3] and [1, 2, 1, 3, 1, 2, 1], but not [3, 2, 3] and [1, 1, 1, 1, 2].
You are given a sequence a consisting of n positive and negative elements (there is no zeros in the sequence).
Your task is to choose maximum by size (length) alternating subsequence of the given sequence (i.e. the sign of each next element is the opposite from the sign of the current element, like positive-negative-positive and so on or negative-positive-negative and so on). Among all such subsequences, you have to choose one which has the maximum sum of elements.
In other words, if the maximum length of alternating subsequence is k then your task is to find the maximum sum of elements of some alternating subsequence of length k.
You have to answer t independent test cases.
Input
The first line of the input contains one integer t (1 ≤ t ≤ 10^4) — the number of test cases. Then t test cases follow.
The first line of the test case contains one integer n (1 ≤ n ≤ 2 ⋅ 10^5) — the number of elements in a. The second line of the test case contains n integers a_1, a_2, ..., a_n (-10^9 ≤ a_i ≤ 10^9, a_i ≠ 0), where a_i is the i-th element of a.
It is guaranteed that the sum of n over all test cases does not exceed 2 ⋅ 10^5 (∑ n ≤ 2 ⋅ 10^5).
Output
For each test case, print the answer — the maximum sum of the maximum by size (length) alternating subsequence of a.
Example
Input
4
5
1 2 3 -1 -2
4
-1 -2 -1 -3
10
-2 8 3 8 -4 -15 5 -2 -3 1
6
1 -1000000000 1 -1000000000 1 -1000000000
Output
2
-1
6
-2999999997
Note
In the first test case of the example, one of the possible answers is [1, 2, \underline{3}, \underline{-1}, -2].
In the second test case of the example, one of the possible answers is [-1, -2, \underline{-1}, -3].
In the third test case of the example, one of the possible answers is [\underline{-2}, 8, 3, \underline{8}, \underline{-4}, -15, \underline{5}, \underline{-2}, -3, \underline{1}].
In the fourth test case of the example, one of the possible answers is [\underline{1}, \underline{-1000000000}, \underline{1}, \underline{-1000000000}, \underline{1}, \underline{-1000000000}].
Submitted Solution:
```
t=int(input())
for _ in range(t):
n=int(input())
arr=list(map(int,input().split()))
prev=arr[0]
maxpo=arr[0]
maxne=min(arr)
sum1=0
for i in range(1,n):
if(arr[i]>0):
if(prev>0):
if(maxpo<arr[i]):
maxpo=arr[i]
prev=arr[i]
else:
sum1=sum1+prev
maxpo=arr[i]
prev=arr[i]
elif(arr[i]<0):
if(prev<0):
if(maxne<arr[i]):
maxne=arr[i]
prev=arr[i]
else:
sum1=sum1+prev
maxne=arr[i]
prev=arr[i]
sum1=sum1+prev
print(sum1)
```
No
| 98,787 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Recall that the sequence b is a a subsequence of the sequence a if b can be derived from a by removing zero or more elements without changing the order of the remaining elements. For example, if a=[1, 2, 1, 3, 1, 2, 1], then possible subsequences are: [1, 1, 1, 1], [3] and [1, 2, 1, 3, 1, 2, 1], but not [3, 2, 3] and [1, 1, 1, 1, 2].
You are given a sequence a consisting of n positive and negative elements (there is no zeros in the sequence).
Your task is to choose maximum by size (length) alternating subsequence of the given sequence (i.e. the sign of each next element is the opposite from the sign of the current element, like positive-negative-positive and so on or negative-positive-negative and so on). Among all such subsequences, you have to choose one which has the maximum sum of elements.
In other words, if the maximum length of alternating subsequence is k then your task is to find the maximum sum of elements of some alternating subsequence of length k.
You have to answer t independent test cases.
Input
The first line of the input contains one integer t (1 ≤ t ≤ 10^4) — the number of test cases. Then t test cases follow.
The first line of the test case contains one integer n (1 ≤ n ≤ 2 ⋅ 10^5) — the number of elements in a. The second line of the test case contains n integers a_1, a_2, ..., a_n (-10^9 ≤ a_i ≤ 10^9, a_i ≠ 0), where a_i is the i-th element of a.
It is guaranteed that the sum of n over all test cases does not exceed 2 ⋅ 10^5 (∑ n ≤ 2 ⋅ 10^5).
Output
For each test case, print the answer — the maximum sum of the maximum by size (length) alternating subsequence of a.
Example
Input
4
5
1 2 3 -1 -2
4
-1 -2 -1 -3
10
-2 8 3 8 -4 -15 5 -2 -3 1
6
1 -1000000000 1 -1000000000 1 -1000000000
Output
2
-1
6
-2999999997
Note
In the first test case of the example, one of the possible answers is [1, 2, \underline{3}, \underline{-1}, -2].
In the second test case of the example, one of the possible answers is [-1, -2, \underline{-1}, -3].
In the third test case of the example, one of the possible answers is [\underline{-2}, 8, 3, \underline{8}, \underline{-4}, -15, \underline{5}, \underline{-2}, -3, \underline{1}].
In the fourth test case of the example, one of the possible answers is [\underline{1}, \underline{-1000000000}, \underline{1}, \underline{-1000000000}, \underline{1}, \underline{-1000000000}].
Submitted Solution:
```
t=int(input())
while(t):
n=int(input())
a=list(map(int,input().rstrip().split()))
c=0
T1=T2=False
ans=0
for i in range(n):
if a[i]>0:
T1=True
if T2:
ans+=c
T2=False
c=a[i]
else:
c=max(c,a[i])
else:
T2=True
if T1:
ans+=c
T1=False
c=a[i]
else:
c=max(c,a[i])
print(ans)
t-=1
```
No
| 98,788 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Recall that the sequence b is a a subsequence of the sequence a if b can be derived from a by removing zero or more elements without changing the order of the remaining elements. For example, if a=[1, 2, 1, 3, 1, 2, 1], then possible subsequences are: [1, 1, 1, 1], [3] and [1, 2, 1, 3, 1, 2, 1], but not [3, 2, 3] and [1, 1, 1, 1, 2].
You are given a sequence a consisting of n positive and negative elements (there is no zeros in the sequence).
Your task is to choose maximum by size (length) alternating subsequence of the given sequence (i.e. the sign of each next element is the opposite from the sign of the current element, like positive-negative-positive and so on or negative-positive-negative and so on). Among all such subsequences, you have to choose one which has the maximum sum of elements.
In other words, if the maximum length of alternating subsequence is k then your task is to find the maximum sum of elements of some alternating subsequence of length k.
You have to answer t independent test cases.
Input
The first line of the input contains one integer t (1 ≤ t ≤ 10^4) — the number of test cases. Then t test cases follow.
The first line of the test case contains one integer n (1 ≤ n ≤ 2 ⋅ 10^5) — the number of elements in a. The second line of the test case contains n integers a_1, a_2, ..., a_n (-10^9 ≤ a_i ≤ 10^9, a_i ≠ 0), where a_i is the i-th element of a.
It is guaranteed that the sum of n over all test cases does not exceed 2 ⋅ 10^5 (∑ n ≤ 2 ⋅ 10^5).
Output
For each test case, print the answer — the maximum sum of the maximum by size (length) alternating subsequence of a.
Example
Input
4
5
1 2 3 -1 -2
4
-1 -2 -1 -3
10
-2 8 3 8 -4 -15 5 -2 -3 1
6
1 -1000000000 1 -1000000000 1 -1000000000
Output
2
-1
6
-2999999997
Note
In the first test case of the example, one of the possible answers is [1, 2, \underline{3}, \underline{-1}, -2].
In the second test case of the example, one of the possible answers is [-1, -2, \underline{-1}, -3].
In the third test case of the example, one of the possible answers is [\underline{-2}, 8, 3, \underline{8}, \underline{-4}, -15, \underline{5}, \underline{-2}, -3, \underline{1}].
In the fourth test case of the example, one of the possible answers is [\underline{1}, \underline{-1000000000}, \underline{1}, \underline{-1000000000}, \underline{1}, \underline{-1000000000}].
Submitted Solution:
```
t=int(input())
for i in range(t):
n=int(input())
a=list(map(int,input().split()))
s=0
t=a[0]
temp=a[0]
for i in range(1,n):
if t>0 and a[i]>0:
temp=max(temp,a[i])
elif t>0 and a[i]<0:
s+=temp
temp=a[i]
t=a[i]
elif t<0 and a[i]<0:
temp=max(a[i],temp)
elif t<0 and a[i]>0:
s+=temp
temp=a[i]
t=a[i]
print(s)
```
No
| 98,789 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Vivek has encountered a problem. He has a maze that can be represented as an n × m grid. Each of the grid cells may represent the following:
* Empty — '.'
* Wall — '#'
* Good person — 'G'
* Bad person — 'B'
The only escape from the maze is at cell (n, m).
A person can move to a cell only if it shares a side with their current cell and does not contain a wall. Vivek wants to block some of the empty cells by replacing them with walls in such a way, that all the good people are able to escape, while none of the bad people are able to. A cell that initially contains 'G' or 'B' cannot be blocked and can be travelled through.
Help him determine if there exists a way to replace some (zero or more) empty cells with walls to satisfy the above conditions.
It is guaranteed that the cell (n,m) is empty. Vivek can also block this cell.
Input
The first line contains one integer t (1 ≤ t ≤ 100) — the number of test cases. The description of the test cases follows.
The first line of each test case contains two integers n, m (1 ≤ n, m ≤ 50) — the number of rows and columns in the maze.
Each of the next n lines contain m characters. They describe the layout of the maze. If a character on a line equals '.', the corresponding cell is empty. If it equals '#', the cell has a wall. 'G' corresponds to a good person and 'B' corresponds to a bad person.
Output
For each test case, print "Yes" if there exists a way to replace some empty cells with walls to satisfy the given conditions. Otherwise print "No"
You may print every letter in any case (upper or lower).
Example
Input
6
1 1
.
1 2
G.
2 2
#B
G.
2 3
G.#
B#.
3 3
#B.
#..
GG.
2 2
#B
B.
Output
Yes
Yes
No
No
Yes
Yes
Note
For the first and second test cases, all conditions are already satisfied.
For the third test case, there is only one empty cell (2,2), and if it is replaced with a wall then the good person at (1,2) will not be able to escape.
For the fourth test case, the good person at (1,1) cannot escape.
For the fifth test case, Vivek can block the cells (2,3) and (2,2).
For the last test case, Vivek can block the destination cell (2, 2).
Tags: constructive algorithms, dfs and similar, dsu, graphs, greedy, implementation, shortest paths
Correct Solution:
```
import sys
import math
sys.setrecursionlimit(1000000) #设置最大递归深度
int1 = lambda x: int(x) - 1 #返回x-1
p2D = lambda x: print(*x, sep="\n") #输出多个元素,以换行符分割
p2S = lambda x: print(*x, sep=" ") #输出多个元素,以空格分割
def II(): return int(sys.stdin.readline()) #读一行(仅一个)整数
def MI(): return map(int, sys.stdin.readline().split()) #读一行数据,转化为int型元组
def LI(): return list(map(int, sys.stdin.readline().split())) #读一行数据,转化为int型列表
def LLI(rows_number): return [LI() for _ in range(rows_number)]
def SI(): return sys.stdin.readline()[:-1] #读一行字符串,舍掉换行符
# 好人G = 2 坏人B = 3 墙# = 1 空气. = 0
Canlevel = True
Gnum = 0
def check(s, tag, ns, ms, n, m, f = 'None'):
if n < 0 or n >= ns or m < 0 or m >= ms:
return
elif s[n][m] == 1 or tag[n][m] == True:
return
elif s[n][m] == 0:
s[n][m] = 1
tag[n][m] = True
elif s[n][m] == 3:
tag[n][m] = True
if f != 'Up':
check(s, tag, ns, ms, n + 1, m, 'Down')
if f != 'Down':
check(s, tag, ns, ms, n - 1, m, 'Up')
if f != 'Right':
check(s, tag, ns, ms, n, m + 1, 'Left')
if f != 'Left':
check(s, tag, ns, ms, n, m - 1, 'Right')
elif s[n][m] == 2:
tag[n][m] = True
global Canlevel
Canlevel = False
return
def level(s, t, ns, ms, n, m, f = 'None'):
if n < 0 or n >= ns or m < 0 or m >= ms:
return
elif s[n][m] == 1 or t[n][m] == True:
return
elif s[n][m] == 3:
global Canlevel
Canlevel = False
return
elif s[n][m] == 0 or s[n][m] == 2:
t[n][m] = True
if s[n][m] == 2:
global Gnum
Gnum += 1
if f != 'Up':
level(s, t, ns, ms, n + 1, m, 'Down')
if f != 'Down':
level(s, t, ns, ms, n - 1, m, 'Up')
if f != 'Right':
level(s, t, ns, ms, n, m + 1, 'Left')
if f != 'Left':
level(s, t, ns, ms, n, m - 1, 'Right')
def main():
_v_ = II()
for __ in range(_v_):
global Canlevel, Gnum
Canlevel = True
Gnum = 0
allG = 0
n, m = MI()
s = []
sn = []
tag = []
taglevel = []
for i in range(n):
s.append(SI())
tag.append([])
taglevel.append([])
for j in range(m):
tag[i].append(False)
taglevel[i].append(False)
for i in range(n):
sn.append([])
for j in range(m):
if s[i][j] == '.':
sn[i].append(0)
if s[i][j] == '#':
sn[i].append(1)
if s[i][j] == 'G':
sn[i].append(2)
allG += 1
if s[i][j] == 'B':
sn[i].append(3)
for i in range(n):
for j in range(m):
if sn[i][j] == 3 and tag[i][j] == False:
check(sn, tag, n, m, i, j)
level(sn, taglevel, n, m, n - 1, m - 1)
if Canlevel == False:
print('No')
elif Gnum == allG:
print('Yes')
else:
print('No')
main()
'''
1
7 10
..##.#G..B
G..#B..G..
G........B
......##.B
.###..B.BB
........##
..........
'''
```
| 98,790 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Vivek has encountered a problem. He has a maze that can be represented as an n × m grid. Each of the grid cells may represent the following:
* Empty — '.'
* Wall — '#'
* Good person — 'G'
* Bad person — 'B'
The only escape from the maze is at cell (n, m).
A person can move to a cell only if it shares a side with their current cell and does not contain a wall. Vivek wants to block some of the empty cells by replacing them with walls in such a way, that all the good people are able to escape, while none of the bad people are able to. A cell that initially contains 'G' or 'B' cannot be blocked and can be travelled through.
Help him determine if there exists a way to replace some (zero or more) empty cells with walls to satisfy the above conditions.
It is guaranteed that the cell (n,m) is empty. Vivek can also block this cell.
Input
The first line contains one integer t (1 ≤ t ≤ 100) — the number of test cases. The description of the test cases follows.
The first line of each test case contains two integers n, m (1 ≤ n, m ≤ 50) — the number of rows and columns in the maze.
Each of the next n lines contain m characters. They describe the layout of the maze. If a character on a line equals '.', the corresponding cell is empty. If it equals '#', the cell has a wall. 'G' corresponds to a good person and 'B' corresponds to a bad person.
Output
For each test case, print "Yes" if there exists a way to replace some empty cells with walls to satisfy the given conditions. Otherwise print "No"
You may print every letter in any case (upper or lower).
Example
Input
6
1 1
.
1 2
G.
2 2
#B
G.
2 3
G.#
B#.
3 3
#B.
#..
GG.
2 2
#B
B.
Output
Yes
Yes
No
No
Yes
Yes
Note
For the first and second test cases, all conditions are already satisfied.
For the third test case, there is only one empty cell (2,2), and if it is replaced with a wall then the good person at (1,2) will not be able to escape.
For the fourth test case, the good person at (1,1) cannot escape.
For the fifth test case, Vivek can block the cells (2,3) and (2,2).
For the last test case, Vivek can block the destination cell (2, 2).
Tags: constructive algorithms, dfs and similar, dsu, graphs, greedy, implementation, shortest paths
Correct Solution:
```
import sys
input = sys.stdin.readline
t=int(input())
ans=[]
for _ in range(t):
h,w=map(int,input().split())
grid=[list(input()) for _ in range(h)]
good=set()
bad=set()
delta=[(-1,0),(1,0),(0,1),(0,-1)]
for i in range(h):
for j in range(w):
if grid[i][j]=="G":
good.add((i,j))
elif grid[i][j]=="B":
bad.add((i,j))
if not good:
ans.append("Yes")
continue
flg=0
for ci,cj in bad:
for di,dj in delta:
ni,nj=ci+di,cj+dj
if 0<=ni<h and 0<=nj<w:
if grid[ni][nj]==".":
grid[ni][nj]="#"
elif grid[ni][nj]=="G":
flg=1
break
if flg:
break
if flg or grid[h-1][w-1]=="#":
ans.append("No")
continue
q=[(h-1,w-1)]
vis=[[0]*w for _ in range(h)]
vis[-1][-1]=1
while q:
ci,cj=q.pop()
for di,dj in delta:
ni,nj=ci+di,cj+dj
if 0<=ni<h and 0<=nj<w and grid[ni][nj]!="#" and not vis[ni][nj]:
vis[ni][nj]=1
q.append((ni,nj))
if all(vis[i][j] for i,j in good):
ans.append("Yes")
else:
ans.append("No")
print("\n".join(ans))
```
| 98,791 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Vivek has encountered a problem. He has a maze that can be represented as an n × m grid. Each of the grid cells may represent the following:
* Empty — '.'
* Wall — '#'
* Good person — 'G'
* Bad person — 'B'
The only escape from the maze is at cell (n, m).
A person can move to a cell only if it shares a side with their current cell and does not contain a wall. Vivek wants to block some of the empty cells by replacing them with walls in such a way, that all the good people are able to escape, while none of the bad people are able to. A cell that initially contains 'G' or 'B' cannot be blocked and can be travelled through.
Help him determine if there exists a way to replace some (zero or more) empty cells with walls to satisfy the above conditions.
It is guaranteed that the cell (n,m) is empty. Vivek can also block this cell.
Input
The first line contains one integer t (1 ≤ t ≤ 100) — the number of test cases. The description of the test cases follows.
The first line of each test case contains two integers n, m (1 ≤ n, m ≤ 50) — the number of rows and columns in the maze.
Each of the next n lines contain m characters. They describe the layout of the maze. If a character on a line equals '.', the corresponding cell is empty. If it equals '#', the cell has a wall. 'G' corresponds to a good person and 'B' corresponds to a bad person.
Output
For each test case, print "Yes" if there exists a way to replace some empty cells with walls to satisfy the given conditions. Otherwise print "No"
You may print every letter in any case (upper or lower).
Example
Input
6
1 1
.
1 2
G.
2 2
#B
G.
2 3
G.#
B#.
3 3
#B.
#..
GG.
2 2
#B
B.
Output
Yes
Yes
No
No
Yes
Yes
Note
For the first and second test cases, all conditions are already satisfied.
For the third test case, there is only one empty cell (2,2), and if it is replaced with a wall then the good person at (1,2) will not be able to escape.
For the fourth test case, the good person at (1,1) cannot escape.
For the fifth test case, Vivek can block the cells (2,3) and (2,2).
For the last test case, Vivek can block the destination cell (2, 2).
Tags: constructive algorithms, dfs and similar, dsu, graphs, greedy, implementation, shortest paths
Correct Solution:
```
def solve(n, m, maze):
for i in range(n):
for j in range(m):
if maze[i][j] != "B":
continue
if i > 0:
if maze[i - 1][j] == "G":
return False
if maze[i - 1][j] == ".":
maze[i - 1][j] = "#"
if j > 0:
if maze[i][j - 1] == "G":
return False
if maze[i][j - 1] == ".":
maze[i][j - 1] = "#"
if i < n - 1:
if maze[i + 1][j] == "G":
return False
if maze[i + 1][j] == ".":
maze[i + 1][j] = "#"
if j < m - 1:
if maze[i][j + 1] == "G":
return False
if maze[i][j + 1] == ".":
maze[i][j + 1] = "#"
reachables = set()
to_visit = {(n - 1, m - 1)} if maze[n - 1][m - 1] != "#" else set()
while to_visit:
i, j = to_visit.pop()
reachables.add((i, j))
if i > 0 and maze[i - 1][j] != '#' and (i - 1, j) not in reachables:
to_visit.add((i - 1, j))
if i < n - 1 and maze[i + 1][j] != '#' and (i + 1, j) not in reachables:
to_visit.add((i + 1, j))
if j > 0 and maze[i][j - 1] != '#' and (i, j - 1) not in reachables:
to_visit.add((i, j - 1))
if j < m - 1 and maze[i][j + 1] != '#' and (i, j + 1) not in reachables:
to_visit.add((i, j + 1))
for i in range(n):
for j in range(m):
if maze[i][j] == "B" and (i, j) in reachables:
return False
if maze[i][j] == "G" and (i, j) not in reachables:
return False
return True
def main():
T = int(input())
for _ in range(T):
n, m = map(int, input().split())
maze = [list(input().strip()) for _ in range(n)]
print("Yes" if solve(n, m, maze) else "No")
if __name__ == "__main__":
main()
```
| 98,792 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Vivek has encountered a problem. He has a maze that can be represented as an n × m grid. Each of the grid cells may represent the following:
* Empty — '.'
* Wall — '#'
* Good person — 'G'
* Bad person — 'B'
The only escape from the maze is at cell (n, m).
A person can move to a cell only if it shares a side with their current cell and does not contain a wall. Vivek wants to block some of the empty cells by replacing them with walls in such a way, that all the good people are able to escape, while none of the bad people are able to. A cell that initially contains 'G' or 'B' cannot be blocked and can be travelled through.
Help him determine if there exists a way to replace some (zero or more) empty cells with walls to satisfy the above conditions.
It is guaranteed that the cell (n,m) is empty. Vivek can also block this cell.
Input
The first line contains one integer t (1 ≤ t ≤ 100) — the number of test cases. The description of the test cases follows.
The first line of each test case contains two integers n, m (1 ≤ n, m ≤ 50) — the number of rows and columns in the maze.
Each of the next n lines contain m characters. They describe the layout of the maze. If a character on a line equals '.', the corresponding cell is empty. If it equals '#', the cell has a wall. 'G' corresponds to a good person and 'B' corresponds to a bad person.
Output
For each test case, print "Yes" if there exists a way to replace some empty cells with walls to satisfy the given conditions. Otherwise print "No"
You may print every letter in any case (upper or lower).
Example
Input
6
1 1
.
1 2
G.
2 2
#B
G.
2 3
G.#
B#.
3 3
#B.
#..
GG.
2 2
#B
B.
Output
Yes
Yes
No
No
Yes
Yes
Note
For the first and second test cases, all conditions are already satisfied.
For the third test case, there is only one empty cell (2,2), and if it is replaced with a wall then the good person at (1,2) will not be able to escape.
For the fourth test case, the good person at (1,1) cannot escape.
For the fifth test case, Vivek can block the cells (2,3) and (2,2).
For the last test case, Vivek can block the destination cell (2, 2).
Tags: constructive algorithms, dfs and similar, dsu, graphs, greedy, implementation, shortest paths
Correct Solution:
```
from sys import stdin
from collections import deque
def fun():
n, m = map(int, stdin.readline().split())
lst = [list(stdin.readline()) for _ in range(n)]
good = []
for x in range(n):
for y in range(m):
if lst[x][y] == 'B':
if x != 0:
if lst[x - 1][y] == 'G':
print('No')
return
elif lst[x - 1][y] == '.':
lst[x - 1][y] = '#'
if x != n - 1:
if lst[x + 1][y] == 'G':
print('No')
return
elif lst[x + 1][y] == '.':
lst[x + 1][y] = '#'
if y != 0:
if lst[x][y - 1] == 'G':
print('No')
return
elif lst[x][y - 1] == '.':
lst[x][y - 1] = '#'
if y != m - 1:
if lst[x][y + 1] == 'G':
print('No')
return
elif lst[x][y + 1] == '.':
lst[x][y + 1] = '#'
elif lst[x][y] == 'G':
good.append((x, y))
if lst[n - 1][m - 1] == 'B':
print('No')
return
done = set()
for r in good:
if r in done:
continue
curr = deque([r])
visi = {r}
done.add(r)
fl = 0
while len(curr):
x = curr.popleft()
if x[0] != 0 and (x[0] - 1, x[1]) not in visi and lst[x[0] - 1][x[1]] == '.' or x[0] != 0 and (
x[0] - 1, x[1]) not in visi and lst[x[0] - 1][x[1]] == 'G':
curr.append((x[0] - 1, x[1]))
visi.add((x[0] - 1, x[1]))
if lst[x[0] - 1][x[1]] == 'G':
done.add((x[0]-1,x[1]))
if x[0] != n - 1 and (x[0] + 1, x[1]) not in visi and lst[x[0] + 1][x[1]] == '.' or x[0] != n - 1 and (
x[0] + 1, x[1]) not in visi and lst[x[0] + 1][x[1]] == 'G':
curr.append((x[0] + 1, x[1]))
visi.add((x[0] + 1, x[1]))
if lst[x[0] + 1][x[1]] == 'G':
done.add((x[0]+1,x[1]))
if x[1] != 0 and (x[0], x[1] - 1) not in visi and lst[x[0]][x[1] - 1] == '.' or x[1] != 0 and (
x[0], x[1] - 1) not in visi and lst[x[0]][x[1] - 1] == 'G':
curr.append((x[0], x[1] - 1))
visi.add((x[0], x[1] - 1))
if lst[x[0]][x[1]-1] == 'G':
done.add((x[0],x[1]-1))
if x[1] != m - 1 and (x[0], x[1] + 1) not in visi and lst[x[0]][x[1] + 1] == '.' or x[1] != m - 1 and (
x[0], x[1] + 1) not in visi and lst[x[0]][x[1] + 1] == 'G':
curr.append((x[0], x[1] + 1))
visi.add((x[0], x[1] + 1))
if lst[x[0]][x[1]+1] == 'G':
done.add((x[0],x[1]+1))
if (n - 1, m - 1) in visi:
fl = 1
break
if not fl:
print('No')
return
print('Yes')
for _ in range(int(stdin.readline())):
fun()
```
| 98,793 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Vivek has encountered a problem. He has a maze that can be represented as an n × m grid. Each of the grid cells may represent the following:
* Empty — '.'
* Wall — '#'
* Good person — 'G'
* Bad person — 'B'
The only escape from the maze is at cell (n, m).
A person can move to a cell only if it shares a side with their current cell and does not contain a wall. Vivek wants to block some of the empty cells by replacing them with walls in such a way, that all the good people are able to escape, while none of the bad people are able to. A cell that initially contains 'G' or 'B' cannot be blocked and can be travelled through.
Help him determine if there exists a way to replace some (zero or more) empty cells with walls to satisfy the above conditions.
It is guaranteed that the cell (n,m) is empty. Vivek can also block this cell.
Input
The first line contains one integer t (1 ≤ t ≤ 100) — the number of test cases. The description of the test cases follows.
The first line of each test case contains two integers n, m (1 ≤ n, m ≤ 50) — the number of rows and columns in the maze.
Each of the next n lines contain m characters. They describe the layout of the maze. If a character on a line equals '.', the corresponding cell is empty. If it equals '#', the cell has a wall. 'G' corresponds to a good person and 'B' corresponds to a bad person.
Output
For each test case, print "Yes" if there exists a way to replace some empty cells with walls to satisfy the given conditions. Otherwise print "No"
You may print every letter in any case (upper or lower).
Example
Input
6
1 1
.
1 2
G.
2 2
#B
G.
2 3
G.#
B#.
3 3
#B.
#..
GG.
2 2
#B
B.
Output
Yes
Yes
No
No
Yes
Yes
Note
For the first and second test cases, all conditions are already satisfied.
For the third test case, there is only one empty cell (2,2), and if it is replaced with a wall then the good person at (1,2) will not be able to escape.
For the fourth test case, the good person at (1,1) cannot escape.
For the fifth test case, Vivek can block the cells (2,3) and (2,2).
For the last test case, Vivek can block the destination cell (2, 2).
Tags: constructive algorithms, dfs and similar, dsu, graphs, greedy, implementation, shortest paths
Correct Solution:
```
import os
import sys
from io import BytesIO, IOBase
# region fastio
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")
# ------------------------------
from math import factorial
from collections import Counter, defaultdict, deque
from heapq import heapify, heappop, heappush
def RL(): return map(int, sys.stdin.readline().rstrip().split())
def RLL(): return list(map(int, sys.stdin.readline().rstrip().split()))
def N(): return int(input())
def comb(n, m): return factorial(n) / (factorial(m) * factorial(n - m)) if n >= m else 0
def perm(n, m): return factorial(n) // (factorial(n - m)) if n >= m else 0
def mdis(x1, y1, x2, y2): return abs(x1 - x2) + abs(y1 - y2)
mod = 998244353
INF = float('inf')
# ------------------------------
def main():
for _ in range(N()):
n, m = RL()
gp = [list(input()) for _ in range(n)]
nex = [[1, 0], [0, 1], [-1, 0], [0, -1]]
gd = 0
bad = 0
tag = False
for i in range(n):
for j in range(m):
if gp[i][j]=='G': gd+=1
if gp[i][j] == 'B':
bad+=1
for xx, yy in nex:
if -1<xx+i<n and -1<yy+j<m and gp[xx+i][yy+j]=='.':
gp[xx+i][yy+j] = '#'
if -1 < xx + i < n and -1 < yy + j < m and gp[xx + i][yy + j] == 'G':
tag = True
if gp[-1][-1]=='B' or tag:
print('No')
elif gp[-1][-1]=='#':
if gd!=0:
print('No')
else:
print('Yes')
else:
q = deque()
q.append((n-1, m-1))
vis = [[0]*m for _ in range(n)]
vis[-1][-1] = 1
if gp[n-1][m-1]=='G':
gd-=1
while q:
px, py = q.popleft()
bd = 0
for xx, yy in nex:
nx, ny = xx+px, yy+py
if -1<nx<n and -1<ny<m and vis[nx][ny]==0:
vis[nx][ny] = 1
if gp[nx][ny] == 'G':
gd-=1
if gp[nx][ny]=='B':
bd+=1
if gp[nx][ny]=='.' or gp[nx][ny]=='G':
q.append((nx, ny))
print('Yes' if gd==0 and bd==0 else 'No')
if __name__ == "__main__":
main()
```
| 98,794 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Vivek has encountered a problem. He has a maze that can be represented as an n × m grid. Each of the grid cells may represent the following:
* Empty — '.'
* Wall — '#'
* Good person — 'G'
* Bad person — 'B'
The only escape from the maze is at cell (n, m).
A person can move to a cell only if it shares a side with their current cell and does not contain a wall. Vivek wants to block some of the empty cells by replacing them with walls in such a way, that all the good people are able to escape, while none of the bad people are able to. A cell that initially contains 'G' or 'B' cannot be blocked and can be travelled through.
Help him determine if there exists a way to replace some (zero or more) empty cells with walls to satisfy the above conditions.
It is guaranteed that the cell (n,m) is empty. Vivek can also block this cell.
Input
The first line contains one integer t (1 ≤ t ≤ 100) — the number of test cases. The description of the test cases follows.
The first line of each test case contains two integers n, m (1 ≤ n, m ≤ 50) — the number of rows and columns in the maze.
Each of the next n lines contain m characters. They describe the layout of the maze. If a character on a line equals '.', the corresponding cell is empty. If it equals '#', the cell has a wall. 'G' corresponds to a good person and 'B' corresponds to a bad person.
Output
For each test case, print "Yes" if there exists a way to replace some empty cells with walls to satisfy the given conditions. Otherwise print "No"
You may print every letter in any case (upper or lower).
Example
Input
6
1 1
.
1 2
G.
2 2
#B
G.
2 3
G.#
B#.
3 3
#B.
#..
GG.
2 2
#B
B.
Output
Yes
Yes
No
No
Yes
Yes
Note
For the first and second test cases, all conditions are already satisfied.
For the third test case, there is only one empty cell (2,2), and if it is replaced with a wall then the good person at (1,2) will not be able to escape.
For the fourth test case, the good person at (1,1) cannot escape.
For the fifth test case, Vivek can block the cells (2,3) and (2,2).
For the last test case, Vivek can block the destination cell (2, 2).
Tags: constructive algorithms, dfs and similar, dsu, graphs, greedy, implementation, shortest paths
Correct Solution:
```
T = int(input().strip())
for t in range(T):
n, m = list(map(int, input().split()))
field = [[1] * (m + 2) for _ in range(n+2)]
bads = []
goods = []
for row in range(n):
cr = input().strip()
for col, cell in enumerate(cr):
if cell == '#':
field[row +1][col +1] = 1
elif cell == 'B':
bads.append((row +1, col +1))
field[row + 1][col + 1] = 0
elif cell == 'G':
goods.append((row +1, col +1))
field[row + 1][col + 1] = 0
else:
field[row +1][col +1] = 0
if len(goods) == 0:
print('Yes')
continue
# print('before:')
# for r in field:
# print("".join(str(c) for c in r))
for b in bads:
for shiftx, shifty in [(1,0), (-1, 0), (0,1), (0, -1)]:
field[b[0]+ shiftx][ b[1] +shifty] = 1
# print('after:')
# for r in field:
# print("".join(str(c) for c in r))
stk = [(n,m)]
if field[n][m] == 1:
print('No')
continue
start = 0
field[n][m] = 2
while start < len(stk):
b = stk[start]
for shiftx, shifty in [(1,0), (-1, 0), (0,1), (0, -1)]:
if field[b[0]+ shiftx] [ b[1] +shifty] == 0:
field[b[0] + shiftx][b[1] + shifty] = 2
stk.append((b[0] + shiftx,b[1] + shifty))
start += 1
good = True
for b in goods:
if field[b[0]][b[1]] != 2:
good = False
break
if good:
print('Yes')
else:
print('No')
# print('passed:')
# for r in field:
# print("".join(str(c) for c in r))
"""
1
5 5
G..#.
.....
..B..
#....
.G...
"""
```
| 98,795 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Vivek has encountered a problem. He has a maze that can be represented as an n × m grid. Each of the grid cells may represent the following:
* Empty — '.'
* Wall — '#'
* Good person — 'G'
* Bad person — 'B'
The only escape from the maze is at cell (n, m).
A person can move to a cell only if it shares a side with their current cell and does not contain a wall. Vivek wants to block some of the empty cells by replacing them with walls in such a way, that all the good people are able to escape, while none of the bad people are able to. A cell that initially contains 'G' or 'B' cannot be blocked and can be travelled through.
Help him determine if there exists a way to replace some (zero or more) empty cells with walls to satisfy the above conditions.
It is guaranteed that the cell (n,m) is empty. Vivek can also block this cell.
Input
The first line contains one integer t (1 ≤ t ≤ 100) — the number of test cases. The description of the test cases follows.
The first line of each test case contains two integers n, m (1 ≤ n, m ≤ 50) — the number of rows and columns in the maze.
Each of the next n lines contain m characters. They describe the layout of the maze. If a character on a line equals '.', the corresponding cell is empty. If it equals '#', the cell has a wall. 'G' corresponds to a good person and 'B' corresponds to a bad person.
Output
For each test case, print "Yes" if there exists a way to replace some empty cells with walls to satisfy the given conditions. Otherwise print "No"
You may print every letter in any case (upper or lower).
Example
Input
6
1 1
.
1 2
G.
2 2
#B
G.
2 3
G.#
B#.
3 3
#B.
#..
GG.
2 2
#B
B.
Output
Yes
Yes
No
No
Yes
Yes
Note
For the first and second test cases, all conditions are already satisfied.
For the third test case, there is only one empty cell (2,2), and if it is replaced with a wall then the good person at (1,2) will not be able to escape.
For the fourth test case, the good person at (1,1) cannot escape.
For the fifth test case, Vivek can block the cells (2,3) and (2,2).
For the last test case, Vivek can block the destination cell (2, 2).
Tags: constructive algorithms, dfs and similar, dsu, graphs, greedy, implementation, shortest paths
Correct Solution:
```
from collections import deque
t = int(input())
for _ in range(t):
n, m = map(int, input().split())
g = [["#"]*(m+2)]
for i in range(n):
g.append(["#"] + list(input()) + ["#"])
g.append(["#"]*(m+2))
for i in range(1, n+1):
for j in range(1, m+1):
if g[i][j] == "B":
if g[i+1][j] == ".":
g[i+1][j] = "#"
if g[i-1][j] == ".":
g[i-1][j] = "#"
if g[i][j+1] == ".":
g[i][j+1] = "#"
if g[i][j-1] == ".":
g[i][j-1] = "#"
visit = [[False]*(m+2) for i in range(n+2)]
visit[n][m] = True
ans = "Yes"
q = deque([(n, m)])
while q:
x, y = q.popleft()
for dx, dy in [(1, 0), (-1, 0), (0, -1), (0, 1)]:
if g[x+dx][y+dy] != "#":
if not visit[x+dx][y+dy]:
q.append((x+dx, y+dy))
visit[x+dx][y+dy] = True
for i in range(1, n+1):
for j in range(1, m+1):
if g[i][j] == "G":
if not visit[i][j]:
ans = "No"
if g[i][j] == "B":
if visit[i][j]:
ans = "No"
f = 0
for i in range(1, n+1):
for j in range(1, m+1):
if g[i][j] == "G":
f = 1
if f == 1:
if g[n][m] == "#":
ans = "No"
else:
ans = "Yes"
print(ans)
```
| 98,796 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Vivek has encountered a problem. He has a maze that can be represented as an n × m grid. Each of the grid cells may represent the following:
* Empty — '.'
* Wall — '#'
* Good person — 'G'
* Bad person — 'B'
The only escape from the maze is at cell (n, m).
A person can move to a cell only if it shares a side with their current cell and does not contain a wall. Vivek wants to block some of the empty cells by replacing them with walls in such a way, that all the good people are able to escape, while none of the bad people are able to. A cell that initially contains 'G' or 'B' cannot be blocked and can be travelled through.
Help him determine if there exists a way to replace some (zero or more) empty cells with walls to satisfy the above conditions.
It is guaranteed that the cell (n,m) is empty. Vivek can also block this cell.
Input
The first line contains one integer t (1 ≤ t ≤ 100) — the number of test cases. The description of the test cases follows.
The first line of each test case contains two integers n, m (1 ≤ n, m ≤ 50) — the number of rows and columns in the maze.
Each of the next n lines contain m characters. They describe the layout of the maze. If a character on a line equals '.', the corresponding cell is empty. If it equals '#', the cell has a wall. 'G' corresponds to a good person and 'B' corresponds to a bad person.
Output
For each test case, print "Yes" if there exists a way to replace some empty cells with walls to satisfy the given conditions. Otherwise print "No"
You may print every letter in any case (upper or lower).
Example
Input
6
1 1
.
1 2
G.
2 2
#B
G.
2 3
G.#
B#.
3 3
#B.
#..
GG.
2 2
#B
B.
Output
Yes
Yes
No
No
Yes
Yes
Note
For the first and second test cases, all conditions are already satisfied.
For the third test case, there is only one empty cell (2,2), and if it is replaced with a wall then the good person at (1,2) will not be able to escape.
For the fourth test case, the good person at (1,1) cannot escape.
For the fifth test case, Vivek can block the cells (2,3) and (2,2).
For the last test case, Vivek can block the destination cell (2, 2).
Tags: constructive algorithms, dfs and similar, dsu, graphs, greedy, implementation, shortest paths
Correct Solution:
```
directions = [(0, 1), (1, 0), (-1, 0), (0, -1)]
def solve(matrix, n,m):
for i in range(n):
for j in range(m):
if matrix[i][j] == 'B':
for di, dj in directions:
ni = i + di
nj = j + dj
if 0<=ni<n and 0<=nj<m:
if matrix[ni][nj] == 'G':
return False
if matrix[ni][nj] != 'B':
matrix[ni][nj] = '#'
q = []
visited = set()
if matrix[-1][-1] != '#':
q.append((n-1, m-1))
visited.add((n-1, m-1))
while q:
i, j = q.pop()
for di, dj in directions:
ni = i + di
nj = j + dj
if (ni, nj) not in visited and 0<=ni<n and 0<=nj<m and matrix[ni][nj] != '#':
q.append((ni, nj))
visited.add((ni, nj))
for i in range(n):
for j in range(m):
if matrix[i][j] == 'G' and (i, j) not in visited:
return False
return True
t = int(input())
for _ in range(t):
n, m = list(map(int, input().split()))
matrix = []
for i in range(n):
matrix.append([x for x in input()])
if solve(matrix, n, m):
print('Yes')
else:
print('No')
```
| 98,797 |
Provide tags and a correct Python 2 solution for this coding contest problem.
Vivek has encountered a problem. He has a maze that can be represented as an n × m grid. Each of the grid cells may represent the following:
* Empty — '.'
* Wall — '#'
* Good person — 'G'
* Bad person — 'B'
The only escape from the maze is at cell (n, m).
A person can move to a cell only if it shares a side with their current cell and does not contain a wall. Vivek wants to block some of the empty cells by replacing them with walls in such a way, that all the good people are able to escape, while none of the bad people are able to. A cell that initially contains 'G' or 'B' cannot be blocked and can be travelled through.
Help him determine if there exists a way to replace some (zero or more) empty cells with walls to satisfy the above conditions.
It is guaranteed that the cell (n,m) is empty. Vivek can also block this cell.
Input
The first line contains one integer t (1 ≤ t ≤ 100) — the number of test cases. The description of the test cases follows.
The first line of each test case contains two integers n, m (1 ≤ n, m ≤ 50) — the number of rows and columns in the maze.
Each of the next n lines contain m characters. They describe the layout of the maze. If a character on a line equals '.', the corresponding cell is empty. If it equals '#', the cell has a wall. 'G' corresponds to a good person and 'B' corresponds to a bad person.
Output
For each test case, print "Yes" if there exists a way to replace some empty cells with walls to satisfy the given conditions. Otherwise print "No"
You may print every letter in any case (upper or lower).
Example
Input
6
1 1
.
1 2
G.
2 2
#B
G.
2 3
G.#
B#.
3 3
#B.
#..
GG.
2 2
#B
B.
Output
Yes
Yes
No
No
Yes
Yes
Note
For the first and second test cases, all conditions are already satisfied.
For the third test case, there is only one empty cell (2,2), and if it is replaced with a wall then the good person at (1,2) will not be able to escape.
For the fourth test case, the good person at (1,1) cannot escape.
For the fifth test case, Vivek can block the cells (2,3) and (2,2).
For the last test case, Vivek can block the destination cell (2, 2).
Tags: constructive algorithms, dfs and similar, dsu, graphs, greedy, implementation, shortest paths
Correct Solution:
```
from sys import stdin, stdout
from collections import Counter, defaultdict
from itertools import permutations, combinations
from fractions import gcd
import heapq
raw_input = stdin.readline
pr = stdout.write
mod=998244353
def ni():
return int(raw_input())
def li():
return list(map(int,raw_input().split()))
def pn(n):
stdout.write(str(n)+'\n')
def pa(arr):
pr(' '.join(map(str,arr))+'\n')
# fast read function for total integer input
def inp():
# this function returns whole input of
# space/line seperated integers
# Use Ctrl+D to flush stdin.
return tuple(map(int,stdin.read().split()))
range = xrange # not for python 3.0+
# main code
for t in range(ni()):
n,m=li()
arr=[]
for i in range(n):
arr.append(list(raw_input().strip()))
f=0
c=0
move=[(0,1),(0,-1),(-1,0),(1,0)]
for i in range(n):
for j in range(m):
if arr[i][j]!='B':
if arr[i][j]=='G':
c+=1
continue
for x,y in move:
px=i+x
py=j+y
if px>=0 and px<n and py>=0 and py<m:
if arr[px][py]=='G':
f=1
break
elif arr[px][py]!='B':
arr[px][py]='#'
if f:
break
if f:
break
if f:
break
if f==0 and c==0:
if arr[-1][-1]!='B':
pr('Yes\n')
else:
pr('No\n')
continue
if f or (c!=0 and (arr[n-1][m-1]=='#' or arr[n-1][m-1]=='B')):
pr('No\n')
continue
q=[(n-1,m-1)]
vis=[[0 for i in range(m)] for j in range(n)]
vis[-1][-1]=1
#print c
while q:
#print q,c
x,y=q.pop(0)
#print x,y
if arr[x][y]=='G':
#print x,y
c-=1
for x1,y1 in move:
px,py=x+x1,y+y1
#print px,py
if px>=0 and px<n and py>=0 and py<m:
if not vis[px][py] and arr[px][py] != '#':
vis[px][py]=1
q.append((px,py))
if c:
pr('No\n')
else:
pr('Yes\n')
```
| 98,798 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Vivek has encountered a problem. He has a maze that can be represented as an n × m grid. Each of the grid cells may represent the following:
* Empty — '.'
* Wall — '#'
* Good person — 'G'
* Bad person — 'B'
The only escape from the maze is at cell (n, m).
A person can move to a cell only if it shares a side with their current cell and does not contain a wall. Vivek wants to block some of the empty cells by replacing them with walls in such a way, that all the good people are able to escape, while none of the bad people are able to. A cell that initially contains 'G' or 'B' cannot be blocked and can be travelled through.
Help him determine if there exists a way to replace some (zero or more) empty cells with walls to satisfy the above conditions.
It is guaranteed that the cell (n,m) is empty. Vivek can also block this cell.
Input
The first line contains one integer t (1 ≤ t ≤ 100) — the number of test cases. The description of the test cases follows.
The first line of each test case contains two integers n, m (1 ≤ n, m ≤ 50) — the number of rows and columns in the maze.
Each of the next n lines contain m characters. They describe the layout of the maze. If a character on a line equals '.', the corresponding cell is empty. If it equals '#', the cell has a wall. 'G' corresponds to a good person and 'B' corresponds to a bad person.
Output
For each test case, print "Yes" if there exists a way to replace some empty cells with walls to satisfy the given conditions. Otherwise print "No"
You may print every letter in any case (upper or lower).
Example
Input
6
1 1
.
1 2
G.
2 2
#B
G.
2 3
G.#
B#.
3 3
#B.
#..
GG.
2 2
#B
B.
Output
Yes
Yes
No
No
Yes
Yes
Note
For the first and second test cases, all conditions are already satisfied.
For the third test case, there is only one empty cell (2,2), and if it is replaced with a wall then the good person at (1,2) will not be able to escape.
For the fourth test case, the good person at (1,1) cannot escape.
For the fifth test case, Vivek can block the cells (2,3) and (2,2).
For the last test case, Vivek can block the destination cell (2, 2).
Submitted Solution:
```
from sys import stdin
from collections import deque
tt = int(stdin.readline())
for loop in range(tt):
n,m = map(int,stdin.readline().split())
a = []
for i in range(n):
tmp = stdin.readline()
a.append(list(tmp[:-1]))
#print (a)
flag = True
goodnum = 0
for i in range(n):
for j in range(m):
if a[i][j] == "B":
if i != 0 and a[i-1][j] == ".":
a[i-1][j] = "#"
if i != n-1 and a[i+1][j] == ".":
a[i+1][j] = "#"
if j != 0 and a[i][j-1] == ".":
a[i][j-1] = "#"
if j != m-1 and a[i][j+1] == ".":
a[i][j+1] = "#"
if i != 0 and a[i-1][j] == "G":
flag = False
if i != n-1 and a[i+1][j] == "G":
flag = False
if j != 0 and a[i][j-1] == "G":
flag = False
if j != m-1 and a[i][j+1] == "G":
flag = False
elif a[i][j] == "G":
goodnum += 1
if not flag or a[-1][-1] == "#":
if goodnum == 0:
print ("Yes")
else:
print ("No")
continue
able = [[True] * m for i in range(n)]
q = deque([(n-1,m-1)])
able[-1][-1] = False
ngood = 0
while len(q) > 0:
x,y = q.popleft()
if a[x][y] == "G":
ngood += 1
i = x
j = y
if x != 0 and a[i-1][j] != "#" and able[i-1][j]:
able[i-1][j] = False
q.append((i-1,j))
if x != n-1 and a[i+1][j] != "#" and able[i+1][j]:
able[i+1][j] = False
q.append((i+1,j))
if y != 0 and a[i][j-1] != "#" and able[i][j-1]:
able[i][j-1] = False
q.append((i,j-1))
if y != m-1 and a[i][j+1] != "#" and able[i][j+1]:
able[i][j+1] = False
q.append((i,j+1))
if ngood == goodnum:
print ("Yes")
else:
print ("No")
```
Yes
| 98,799 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.