text stringlengths 198 433k | conversation_id int64 0 109k |
|---|---|
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
On February 14 Denis decided to give Valentine to Nastya and did not come up with anything better than to draw a huge red heart on the door of the length k (k β₯ 3). Nastya was very confused by this present, so she decided to break the door, throwing it on the mountains.
Mountains are described by a sequence of heights a_1, a_2, ..., a_n in order from left to right (k β€ n). It is guaranteed that neighboring heights are not equal to each other (that is, a_i β a_{i+1} for all i from 1 to n-1).
Peaks of mountains on the segment [l,r] (from l to r) are called indexes i such that l < i < r, a_{i - 1} < a_i and a_i > a_{i + 1}. It is worth noting that the boundary indexes l and r for the segment are not peaks. For example, if n=8 and a=[3,1,4,1,5,9,2,6], then the segment [1,8] has only two peaks (with indexes 3 and 6), and there are no peaks on the segment [3, 6].
To break the door, Nastya throws it to a segment [l,l+k-1] of consecutive mountains of length k (1 β€ l β€ n-k+1). When the door touches the peaks of the mountains, it breaks into two parts, after that these parts will continue to fall in different halves and also break into pieces when touching the peaks of the mountains, and so on. Formally, the number of parts that the door will break into will be equal to p+1, where p is the number of peaks on the segment [l,l+k-1].
Nastya wants to break it into as many pieces as possible. Help her choose such a segment of mountains [l, l+k-1] that the number of peaks on it is maximum. If there are several optimal segments, Nastya wants to find one for which the value l is minimal.
Formally, you need to choose a segment of mountains [l, l+k-1] that has the maximum number of peaks. Among all such segments, you need to find the segment that has the minimum possible value l.
Input
The first line contains an integer t (1 β€ t β€ 10^4) β the number of test cases. Then the descriptions of the test cases follow.
The first line of each test case contains two integers n and k (3 β€ k β€ n β€ 2 β
10^5) β the number of mountains and the length of the door.
The second line of the input data set contains n integers a_1, a_2, ..., a_n (0 β€ a_i β€ 10 ^ 9, a_i β a_{i + 1}) β the heights of mountains.
It is guaranteed that the sum of n over all the test cases will not exceed 2 β
10^5.
Output
For each test case, output two integers t and l β the maximum number of parts that the door can split into, and the left border of the segment of length k that the door should be reset to.
Example
Input
5
8 6
1 2 4 1 2 4 1 2
5 3
3 2 3 2 1
10 4
4 3 4 3 2 3 2 1 0 1
15 7
3 7 4 8 2 3 4 5 21 2 3 4 2 1 3
7 5
1 2 3 4 5 6 1
Output
3 2
2 2
2 1
3 1
2 3
Note
In the first example, you need to select a segment of mountains from 2 to 7. In this segment, the indexes 3 and 6 are peaks, so the answer is 3 (only 2 peaks, so the door will break into 3 parts). It is not difficult to notice that the mountain segments [1, 6] and [3, 8] are not suitable since they only have a 1 peak (for the first segment, the 6 index is not a peak, and for the second segment, the 3 index is not a peak).
In the second example, you need to select a segment of mountains from 2 to 4. In this segment, the index 3 is a peak, so the answer is 2 (only 1 peak, so the door will break into 2 parts).
In the third example, you need to select a segment of mountains from 1 to 4. In this segment, the index 3 is a peak, so the answer is 2 (only 1 peak, so the door will break into 2 parts). You can see that on the segments [2, 5], [4, 7] and [5, 8] the number of peaks is also 1, but these segments have a left border greater than the segment [1, 4], so they are not the correct answer.
Submitted Solution:
```
from itertools import accumulate
for ii in range(int(input())):
n , k = map(int , input().split())
arr = list(map(int , input().split()))
peaks = [0]*n
p_sum = [0]*n
for i in range(1 , n-1):
if arr[i-1] < arr[i] > arr[i+1]:
peaks[i] = 1
p_sum[i] = peaks[i] + p_sum[i-1]
p_sum[n-1] = p_sum[n-2]
#print(p_sum)
p = p_sum[k-2] - p_sum[0]
#p = 0
ind = 0
i = 1
while i + k - 1 < n :
temp = p_sum[i+k-2] - p_sum[i]
if temp > p:
p = temp
ind = i
i+=1
print(p +1 , ind+1)
```
Yes
| 90,300 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
On February 14 Denis decided to give Valentine to Nastya and did not come up with anything better than to draw a huge red heart on the door of the length k (k β₯ 3). Nastya was very confused by this present, so she decided to break the door, throwing it on the mountains.
Mountains are described by a sequence of heights a_1, a_2, ..., a_n in order from left to right (k β€ n). It is guaranteed that neighboring heights are not equal to each other (that is, a_i β a_{i+1} for all i from 1 to n-1).
Peaks of mountains on the segment [l,r] (from l to r) are called indexes i such that l < i < r, a_{i - 1} < a_i and a_i > a_{i + 1}. It is worth noting that the boundary indexes l and r for the segment are not peaks. For example, if n=8 and a=[3,1,4,1,5,9,2,6], then the segment [1,8] has only two peaks (with indexes 3 and 6), and there are no peaks on the segment [3, 6].
To break the door, Nastya throws it to a segment [l,l+k-1] of consecutive mountains of length k (1 β€ l β€ n-k+1). When the door touches the peaks of the mountains, it breaks into two parts, after that these parts will continue to fall in different halves and also break into pieces when touching the peaks of the mountains, and so on. Formally, the number of parts that the door will break into will be equal to p+1, where p is the number of peaks on the segment [l,l+k-1].
Nastya wants to break it into as many pieces as possible. Help her choose such a segment of mountains [l, l+k-1] that the number of peaks on it is maximum. If there are several optimal segments, Nastya wants to find one for which the value l is minimal.
Formally, you need to choose a segment of mountains [l, l+k-1] that has the maximum number of peaks. Among all such segments, you need to find the segment that has the minimum possible value l.
Input
The first line contains an integer t (1 β€ t β€ 10^4) β the number of test cases. Then the descriptions of the test cases follow.
The first line of each test case contains two integers n and k (3 β€ k β€ n β€ 2 β
10^5) β the number of mountains and the length of the door.
The second line of the input data set contains n integers a_1, a_2, ..., a_n (0 β€ a_i β€ 10 ^ 9, a_i β a_{i + 1}) β the heights of mountains.
It is guaranteed that the sum of n over all the test cases will not exceed 2 β
10^5.
Output
For each test case, output two integers t and l β the maximum number of parts that the door can split into, and the left border of the segment of length k that the door should be reset to.
Example
Input
5
8 6
1 2 4 1 2 4 1 2
5 3
3 2 3 2 1
10 4
4 3 4 3 2 3 2 1 0 1
15 7
3 7 4 8 2 3 4 5 21 2 3 4 2 1 3
7 5
1 2 3 4 5 6 1
Output
3 2
2 2
2 1
3 1
2 3
Note
In the first example, you need to select a segment of mountains from 2 to 7. In this segment, the indexes 3 and 6 are peaks, so the answer is 3 (only 2 peaks, so the door will break into 3 parts). It is not difficult to notice that the mountain segments [1, 6] and [3, 8] are not suitable since they only have a 1 peak (for the first segment, the 6 index is not a peak, and for the second segment, the 3 index is not a peak).
In the second example, you need to select a segment of mountains from 2 to 4. In this segment, the index 3 is a peak, so the answer is 2 (only 1 peak, so the door will break into 2 parts).
In the third example, you need to select a segment of mountains from 1 to 4. In this segment, the index 3 is a peak, so the answer is 2 (only 1 peak, so the door will break into 2 parts). You can see that on the segments [2, 5], [4, 7] and [5, 8] the number of peaks is also 1, but these segments have a left border greater than the segment [1, 4], so they are not the correct answer.
Submitted Solution:
```
import os
import sys
from io import BytesIO, IOBase
def solution(arr, n, k):
pre = [0] * n
for i in range(1, n - 1):
if arr[i - 1] < arr[i] > arr[i + 1]:
pre[i] = 1
for i in range(1, n):
pre[i] += pre[i - 1]
start = k - 2
l, res = 0, -1
for i in range(start, n):
prev = res
res = max(res, pre[i] - pre[i - k + 2])
if res > prev:
l = i - k + 2
write(res + 1, l + 1)
def main():
for _ in range(r_int()):
n, k = r_array()
arr = r_array()
solution(arr, n, k)
# 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)
def input():
return sys.stdin.readline().rstrip("\r\n")
def write(*args, end='\n'):
for x in args[:-1]:
sys.stdout.write(str(x) + ' ')
sys.stdout.write(str(args[-1]))
sys.stdout.write(end)
def r_array():
return [int(x) for x in input().split()]
def r_int():
return int(input())
if __name__ == "__main__":
main()
```
Yes
| 90,301 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
On February 14 Denis decided to give Valentine to Nastya and did not come up with anything better than to draw a huge red heart on the door of the length k (k β₯ 3). Nastya was very confused by this present, so she decided to break the door, throwing it on the mountains.
Mountains are described by a sequence of heights a_1, a_2, ..., a_n in order from left to right (k β€ n). It is guaranteed that neighboring heights are not equal to each other (that is, a_i β a_{i+1} for all i from 1 to n-1).
Peaks of mountains on the segment [l,r] (from l to r) are called indexes i such that l < i < r, a_{i - 1} < a_i and a_i > a_{i + 1}. It is worth noting that the boundary indexes l and r for the segment are not peaks. For example, if n=8 and a=[3,1,4,1,5,9,2,6], then the segment [1,8] has only two peaks (with indexes 3 and 6), and there are no peaks on the segment [3, 6].
To break the door, Nastya throws it to a segment [l,l+k-1] of consecutive mountains of length k (1 β€ l β€ n-k+1). When the door touches the peaks of the mountains, it breaks into two parts, after that these parts will continue to fall in different halves and also break into pieces when touching the peaks of the mountains, and so on. Formally, the number of parts that the door will break into will be equal to p+1, where p is the number of peaks on the segment [l,l+k-1].
Nastya wants to break it into as many pieces as possible. Help her choose such a segment of mountains [l, l+k-1] that the number of peaks on it is maximum. If there are several optimal segments, Nastya wants to find one for which the value l is minimal.
Formally, you need to choose a segment of mountains [l, l+k-1] that has the maximum number of peaks. Among all such segments, you need to find the segment that has the minimum possible value l.
Input
The first line contains an integer t (1 β€ t β€ 10^4) β the number of test cases. Then the descriptions of the test cases follow.
The first line of each test case contains two integers n and k (3 β€ k β€ n β€ 2 β
10^5) β the number of mountains and the length of the door.
The second line of the input data set contains n integers a_1, a_2, ..., a_n (0 β€ a_i β€ 10 ^ 9, a_i β a_{i + 1}) β the heights of mountains.
It is guaranteed that the sum of n over all the test cases will not exceed 2 β
10^5.
Output
For each test case, output two integers t and l β the maximum number of parts that the door can split into, and the left border of the segment of length k that the door should be reset to.
Example
Input
5
8 6
1 2 4 1 2 4 1 2
5 3
3 2 3 2 1
10 4
4 3 4 3 2 3 2 1 0 1
15 7
3 7 4 8 2 3 4 5 21 2 3 4 2 1 3
7 5
1 2 3 4 5 6 1
Output
3 2
2 2
2 1
3 1
2 3
Note
In the first example, you need to select a segment of mountains from 2 to 7. In this segment, the indexes 3 and 6 are peaks, so the answer is 3 (only 2 peaks, so the door will break into 3 parts). It is not difficult to notice that the mountain segments [1, 6] and [3, 8] are not suitable since they only have a 1 peak (for the first segment, the 6 index is not a peak, and for the second segment, the 3 index is not a peak).
In the second example, you need to select a segment of mountains from 2 to 4. In this segment, the index 3 is a peak, so the answer is 2 (only 1 peak, so the door will break into 2 parts).
In the third example, you need to select a segment of mountains from 1 to 4. In this segment, the index 3 is a peak, so the answer is 2 (only 1 peak, so the door will break into 2 parts). You can see that on the segments [2, 5], [4, 7] and [5, 8] the number of peaks is also 1, but these segments have a left border greater than the segment [1, 4], so they are not the correct answer.
Submitted Solution:
```
for _ in range(int(input())):
n,k=map(int,input().split())
l=list(map(int,input().split()))
x=[]
p=0
for i in range(1,k-1):
if l[i]>l[i-1] and l[i]>l[i+1]:
x.append(i)
p+=1
m=0
y=0
b=p
for i in range(1,n-k+1):
if i in x:
p=p-1
if l[i+k-2]>l[i+k-3] and l[i+k-2]>l[i+k-1]:
p+=1
if p==b:
m=min(i,m)
if p>b:
b=p
m=i
print(b+1,m+1)
```
No
| 90,302 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
On February 14 Denis decided to give Valentine to Nastya and did not come up with anything better than to draw a huge red heart on the door of the length k (k β₯ 3). Nastya was very confused by this present, so she decided to break the door, throwing it on the mountains.
Mountains are described by a sequence of heights a_1, a_2, ..., a_n in order from left to right (k β€ n). It is guaranteed that neighboring heights are not equal to each other (that is, a_i β a_{i+1} for all i from 1 to n-1).
Peaks of mountains on the segment [l,r] (from l to r) are called indexes i such that l < i < r, a_{i - 1} < a_i and a_i > a_{i + 1}. It is worth noting that the boundary indexes l and r for the segment are not peaks. For example, if n=8 and a=[3,1,4,1,5,9,2,6], then the segment [1,8] has only two peaks (with indexes 3 and 6), and there are no peaks on the segment [3, 6].
To break the door, Nastya throws it to a segment [l,l+k-1] of consecutive mountains of length k (1 β€ l β€ n-k+1). When the door touches the peaks of the mountains, it breaks into two parts, after that these parts will continue to fall in different halves and also break into pieces when touching the peaks of the mountains, and so on. Formally, the number of parts that the door will break into will be equal to p+1, where p is the number of peaks on the segment [l,l+k-1].
Nastya wants to break it into as many pieces as possible. Help her choose such a segment of mountains [l, l+k-1] that the number of peaks on it is maximum. If there are several optimal segments, Nastya wants to find one for which the value l is minimal.
Formally, you need to choose a segment of mountains [l, l+k-1] that has the maximum number of peaks. Among all such segments, you need to find the segment that has the minimum possible value l.
Input
The first line contains an integer t (1 β€ t β€ 10^4) β the number of test cases. Then the descriptions of the test cases follow.
The first line of each test case contains two integers n and k (3 β€ k β€ n β€ 2 β
10^5) β the number of mountains and the length of the door.
The second line of the input data set contains n integers a_1, a_2, ..., a_n (0 β€ a_i β€ 10 ^ 9, a_i β a_{i + 1}) β the heights of mountains.
It is guaranteed that the sum of n over all the test cases will not exceed 2 β
10^5.
Output
For each test case, output two integers t and l β the maximum number of parts that the door can split into, and the left border of the segment of length k that the door should be reset to.
Example
Input
5
8 6
1 2 4 1 2 4 1 2
5 3
3 2 3 2 1
10 4
4 3 4 3 2 3 2 1 0 1
15 7
3 7 4 8 2 3 4 5 21 2 3 4 2 1 3
7 5
1 2 3 4 5 6 1
Output
3 2
2 2
2 1
3 1
2 3
Note
In the first example, you need to select a segment of mountains from 2 to 7. In this segment, the indexes 3 and 6 are peaks, so the answer is 3 (only 2 peaks, so the door will break into 3 parts). It is not difficult to notice that the mountain segments [1, 6] and [3, 8] are not suitable since they only have a 1 peak (for the first segment, the 6 index is not a peak, and for the second segment, the 3 index is not a peak).
In the second example, you need to select a segment of mountains from 2 to 4. In this segment, the index 3 is a peak, so the answer is 2 (only 1 peak, so the door will break into 2 parts).
In the third example, you need to select a segment of mountains from 1 to 4. In this segment, the index 3 is a peak, so the answer is 2 (only 1 peak, so the door will break into 2 parts). You can see that on the segments [2, 5], [4, 7] and [5, 8] the number of peaks is also 1, but these segments have a left border greater than the segment [1, 4], so they are not the correct answer.
Submitted Solution:
```
for _ in range((int)(input())):
a=list(map(int,input().split()))
k=a[1]
l=list(map(int,input().split()))
i,t,f=1,[],0
t.append(0)
while i<len(l):
if l[i]>l[i-1]:
if i-2>=0:
if l[i-2]<l[i-1]:
t[i-1]=0
t.append(1)
else:
t.append(0)
i+=1
summ=[0]*len(t)
t[-1]=0
i=1
summ[0]=t[0]
while i<len(t):
summ[i]=summ[i-1]+t[i]
i+=1
i=k-1
maxi,index=0,0
while i<len(summ):
if summ[i]==summ[i-1]+1:
if summ[i-1]-summ[i-k]>maxi:
maxi=summ[i-1]-summ[i-k+1]
index=i-k+1
elif summ[i]-summ[i-k+1]>maxi:
index=i-k+1
# print(i)
maxi=summ[i]-summ[i-k+1]
i+=1
print(maxi+1,index+1)
```
No
| 90,303 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
On February 14 Denis decided to give Valentine to Nastya and did not come up with anything better than to draw a huge red heart on the door of the length k (k β₯ 3). Nastya was very confused by this present, so she decided to break the door, throwing it on the mountains.
Mountains are described by a sequence of heights a_1, a_2, ..., a_n in order from left to right (k β€ n). It is guaranteed that neighboring heights are not equal to each other (that is, a_i β a_{i+1} for all i from 1 to n-1).
Peaks of mountains on the segment [l,r] (from l to r) are called indexes i such that l < i < r, a_{i - 1} < a_i and a_i > a_{i + 1}. It is worth noting that the boundary indexes l and r for the segment are not peaks. For example, if n=8 and a=[3,1,4,1,5,9,2,6], then the segment [1,8] has only two peaks (with indexes 3 and 6), and there are no peaks on the segment [3, 6].
To break the door, Nastya throws it to a segment [l,l+k-1] of consecutive mountains of length k (1 β€ l β€ n-k+1). When the door touches the peaks of the mountains, it breaks into two parts, after that these parts will continue to fall in different halves and also break into pieces when touching the peaks of the mountains, and so on. Formally, the number of parts that the door will break into will be equal to p+1, where p is the number of peaks on the segment [l,l+k-1].
Nastya wants to break it into as many pieces as possible. Help her choose such a segment of mountains [l, l+k-1] that the number of peaks on it is maximum. If there are several optimal segments, Nastya wants to find one for which the value l is minimal.
Formally, you need to choose a segment of mountains [l, l+k-1] that has the maximum number of peaks. Among all such segments, you need to find the segment that has the minimum possible value l.
Input
The first line contains an integer t (1 β€ t β€ 10^4) β the number of test cases. Then the descriptions of the test cases follow.
The first line of each test case contains two integers n and k (3 β€ k β€ n β€ 2 β
10^5) β the number of mountains and the length of the door.
The second line of the input data set contains n integers a_1, a_2, ..., a_n (0 β€ a_i β€ 10 ^ 9, a_i β a_{i + 1}) β the heights of mountains.
It is guaranteed that the sum of n over all the test cases will not exceed 2 β
10^5.
Output
For each test case, output two integers t and l β the maximum number of parts that the door can split into, and the left border of the segment of length k that the door should be reset to.
Example
Input
5
8 6
1 2 4 1 2 4 1 2
5 3
3 2 3 2 1
10 4
4 3 4 3 2 3 2 1 0 1
15 7
3 7 4 8 2 3 4 5 21 2 3 4 2 1 3
7 5
1 2 3 4 5 6 1
Output
3 2
2 2
2 1
3 1
2 3
Note
In the first example, you need to select a segment of mountains from 2 to 7. In this segment, the indexes 3 and 6 are peaks, so the answer is 3 (only 2 peaks, so the door will break into 3 parts). It is not difficult to notice that the mountain segments [1, 6] and [3, 8] are not suitable since they only have a 1 peak (for the first segment, the 6 index is not a peak, and for the second segment, the 3 index is not a peak).
In the second example, you need to select a segment of mountains from 2 to 4. In this segment, the index 3 is a peak, so the answer is 2 (only 1 peak, so the door will break into 2 parts).
In the third example, you need to select a segment of mountains from 1 to 4. In this segment, the index 3 is a peak, so the answer is 2 (only 1 peak, so the door will break into 2 parts). You can see that on the segments [2, 5], [4, 7] and [5, 8] the number of peaks is also 1, but these segments have a left border greater than the segment [1, 4], so they are not the correct answer.
Submitted Solution:
```
t = int(input())
for u in range(t):
n,k = list(map(int,input().split()))
a = list(map(int,input().split()))
picks = [0]*n
count = [0]*(n-k+1)
tmp = 0
tmpact = [0,0]
for i in range(1,n-1):
if a[i] > a[i-1] and a[i] > a[i+1]:
picks[i] = 1
for i in range(k-2):
if picks[i] == 1:
tmp += 1
count[0] = tmp
for i in range(k-1,n):
if picks[i-k+1] == 1:
tmp -= 1
if picks[i-1] == 1:
tmp += 1
count[i-k+1] = tmp
for i in range(n-k+1):
if count[i] > tmpact[0]:
tmpact[1] = i+1
tmpact[0] = count[i]
print(tmpact[0]+1,tmpact[1])
```
No
| 90,304 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
On February 14 Denis decided to give Valentine to Nastya and did not come up with anything better than to draw a huge red heart on the door of the length k (k β₯ 3). Nastya was very confused by this present, so she decided to break the door, throwing it on the mountains.
Mountains are described by a sequence of heights a_1, a_2, ..., a_n in order from left to right (k β€ n). It is guaranteed that neighboring heights are not equal to each other (that is, a_i β a_{i+1} for all i from 1 to n-1).
Peaks of mountains on the segment [l,r] (from l to r) are called indexes i such that l < i < r, a_{i - 1} < a_i and a_i > a_{i + 1}. It is worth noting that the boundary indexes l and r for the segment are not peaks. For example, if n=8 and a=[3,1,4,1,5,9,2,6], then the segment [1,8] has only two peaks (with indexes 3 and 6), and there are no peaks on the segment [3, 6].
To break the door, Nastya throws it to a segment [l,l+k-1] of consecutive mountains of length k (1 β€ l β€ n-k+1). When the door touches the peaks of the mountains, it breaks into two parts, after that these parts will continue to fall in different halves and also break into pieces when touching the peaks of the mountains, and so on. Formally, the number of parts that the door will break into will be equal to p+1, where p is the number of peaks on the segment [l,l+k-1].
Nastya wants to break it into as many pieces as possible. Help her choose such a segment of mountains [l, l+k-1] that the number of peaks on it is maximum. If there are several optimal segments, Nastya wants to find one for which the value l is minimal.
Formally, you need to choose a segment of mountains [l, l+k-1] that has the maximum number of peaks. Among all such segments, you need to find the segment that has the minimum possible value l.
Input
The first line contains an integer t (1 β€ t β€ 10^4) β the number of test cases. Then the descriptions of the test cases follow.
The first line of each test case contains two integers n and k (3 β€ k β€ n β€ 2 β
10^5) β the number of mountains and the length of the door.
The second line of the input data set contains n integers a_1, a_2, ..., a_n (0 β€ a_i β€ 10 ^ 9, a_i β a_{i + 1}) β the heights of mountains.
It is guaranteed that the sum of n over all the test cases will not exceed 2 β
10^5.
Output
For each test case, output two integers t and l β the maximum number of parts that the door can split into, and the left border of the segment of length k that the door should be reset to.
Example
Input
5
8 6
1 2 4 1 2 4 1 2
5 3
3 2 3 2 1
10 4
4 3 4 3 2 3 2 1 0 1
15 7
3 7 4 8 2 3 4 5 21 2 3 4 2 1 3
7 5
1 2 3 4 5 6 1
Output
3 2
2 2
2 1
3 1
2 3
Note
In the first example, you need to select a segment of mountains from 2 to 7. In this segment, the indexes 3 and 6 are peaks, so the answer is 3 (only 2 peaks, so the door will break into 3 parts). It is not difficult to notice that the mountain segments [1, 6] and [3, 8] are not suitable since they only have a 1 peak (for the first segment, the 6 index is not a peak, and for the second segment, the 3 index is not a peak).
In the second example, you need to select a segment of mountains from 2 to 4. In this segment, the index 3 is a peak, so the answer is 2 (only 1 peak, so the door will break into 2 parts).
In the third example, you need to select a segment of mountains from 1 to 4. In this segment, the index 3 is a peak, so the answer is 2 (only 1 peak, so the door will break into 2 parts). You can see that on the segments [2, 5], [4, 7] and [5, 8] the number of peaks is also 1, but these segments have a left border greater than the segment [1, 4], so they are not the correct answer.
Submitted Solution:
```
from itertools import accumulate
for _ in range(int(input())):
n,k = map(int,input().split())
a = list(map(int,input().split()))
p = [0]*n
q = [0]*n
for i in range(1,n-1):
if a[i-1]<a[i] and a[i]>a[i+1]:
p[i]=1
q[i+1]=1
p = list(accumulate(p))
q = list(accumulate(q))
maxi = 0
#print(p)
#print(q)
for i in range(n-k+1):
if q[i+k-1]-p[i]>maxi:
maxi=q[i+k-1]-p[i]
idx = i+1
count = q[i+k-1]-p[i]
try:
print(count+1,idx)
except:
print(1,1)
```
No
| 90,305 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Shubham has a binary string s. A binary string is a string containing only characters "0" and "1".
He can perform the following operation on the string any amount of times:
* Select an index of the string, and flip the character at that index. This means, if the character was "0", it becomes "1", and vice versa.
A string is called good if it does not contain "010" or "101" as a subsequence β for instance, "1001" contains "101" as a subsequence, hence it is not a good string, while "1000" doesn't contain neither "010" nor "101" as subsequences, so it is a good string.
What is the minimum number of operations he will have to perform, so that the string becomes good? It can be shown that with these operations we can make any string good.
A string a is a subsequence of a string b if a can be obtained from b by deletion of several (possibly, zero or all) characters.
Input
The first line of the input contains a single integer t (1β€ t β€ 100) β the number of test cases.
Each of the next t lines contains a binary string s (1 β€ |s| β€ 1000).
Output
For every string, output the minimum number of operations required to make it good.
Example
Input
7
001
100
101
010
0
1
001100
Output
0
0
1
1
0
0
2
Note
In test cases 1, 2, 5, 6 no operations are required since they are already good strings.
For the 3rd test case: "001" can be achieved by flipping the first character β and is one of the possible ways to get a good string.
For the 4th test case: "000" can be achieved by flipping the second character β and is one of the possible ways to get a good string.
For the 7th test case: "000000" can be achieved by flipping the third and fourth characters β and is one of the possible ways to get a good string.
Tags: implementation, strings
Correct Solution:
```
import sys,math
for _ in range(int(input())):
s=list(map(int,list(input())))
cost=0
cost1=0
mi=10**9
n=len(s)
for i in range(n):
cost=0
cost1=0
for j in range(n):
if j<=i:
if (s[j]==0):
cost+=1
else:
cost1+=1
else:
if (s[j]==1):
cost+=1
else:
cost1+=1
#print("cost = ",cost," cost1 = ",cost1)
mi=min(mi,min(cost,cost1))
print(mi)
```
| 90,306 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Shubham has a binary string s. A binary string is a string containing only characters "0" and "1".
He can perform the following operation on the string any amount of times:
* Select an index of the string, and flip the character at that index. This means, if the character was "0", it becomes "1", and vice versa.
A string is called good if it does not contain "010" or "101" as a subsequence β for instance, "1001" contains "101" as a subsequence, hence it is not a good string, while "1000" doesn't contain neither "010" nor "101" as subsequences, so it is a good string.
What is the minimum number of operations he will have to perform, so that the string becomes good? It can be shown that with these operations we can make any string good.
A string a is a subsequence of a string b if a can be obtained from b by deletion of several (possibly, zero or all) characters.
Input
The first line of the input contains a single integer t (1β€ t β€ 100) β the number of test cases.
Each of the next t lines contains a binary string s (1 β€ |s| β€ 1000).
Output
For every string, output the minimum number of operations required to make it good.
Example
Input
7
001
100
101
010
0
1
001100
Output
0
0
1
1
0
0
2
Note
In test cases 1, 2, 5, 6 no operations are required since they are already good strings.
For the 3rd test case: "001" can be achieved by flipping the first character β and is one of the possible ways to get a good string.
For the 4th test case: "000" can be achieved by flipping the second character β and is one of the possible ways to get a good string.
For the 7th test case: "000000" can be achieved by flipping the third and fourth characters β and is one of the possible ways to get a good string.
Tags: implementation, strings
Correct Solution:
```
n=int(input())
for i in range(n):
j=input()
if list(j)==sorted(j) or list(j)==sorted(j)[::-1]:
print(0)
else:
x, y=j.count("1"), j.count("0")
a, b, c, d=0, y, 0, x
new=[y, x]
for k in j:
if k=="1":
a+=1
d-=1
else:
b-=1
c+=1
new.extend([a+b, c+d])
print(min(new))
```
| 90,307 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Shubham has a binary string s. A binary string is a string containing only characters "0" and "1".
He can perform the following operation on the string any amount of times:
* Select an index of the string, and flip the character at that index. This means, if the character was "0", it becomes "1", and vice versa.
A string is called good if it does not contain "010" or "101" as a subsequence β for instance, "1001" contains "101" as a subsequence, hence it is not a good string, while "1000" doesn't contain neither "010" nor "101" as subsequences, so it is a good string.
What is the minimum number of operations he will have to perform, so that the string becomes good? It can be shown that with these operations we can make any string good.
A string a is a subsequence of a string b if a can be obtained from b by deletion of several (possibly, zero or all) characters.
Input
The first line of the input contains a single integer t (1β€ t β€ 100) β the number of test cases.
Each of the next t lines contains a binary string s (1 β€ |s| β€ 1000).
Output
For every string, output the minimum number of operations required to make it good.
Example
Input
7
001
100
101
010
0
1
001100
Output
0
0
1
1
0
0
2
Note
In test cases 1, 2, 5, 6 no operations are required since they are already good strings.
For the 3rd test case: "001" can be achieved by flipping the first character β and is one of the possible ways to get a good string.
For the 4th test case: "000" can be achieved by flipping the second character β and is one of the possible ways to get a good string.
For the 7th test case: "000000" can be achieved by flipping the third and fourth characters β and is one of the possible ways to get a good string.
Tags: implementation, strings
Correct Solution:
```
## necessary imports
import sys
input = sys.stdin.readline
from math import ceil, floor;
# swap_array function
def swaparr(arr, a,b):
temp = arr[a];
arr[a] = arr[b];
arr[b] = temp
## gcd function
def gcd(a,b):
if a == 0:
return b
return gcd(b%a, a)
## nCr function efficient using Binomial Cofficient
def nCr(n, k):
if(k > n - k):
k = n - k
res = 1
for i in range(k):
res = res * (n - i)
res = res / (i + 1)
return int(res)
## upper bound function code -- such that e in a[:i] e < x;
def upper_bound(a, x, lo=0):
hi = len(a)
while lo < hi:
mid = (lo+hi)//2
if a[mid] < x:
lo = mid+1
else:
hi = mid
return lo
## prime factorization
def primefs(n):
## if n == 1 ## calculating primes
primes = {}
while(n%2 == 0):
primes[2] = primes.get(2, 0) + 1
n = n//2
for i in range(3, int(n**0.5)+2, 2):
while(n%i == 0):
primes[i] = primes.get(i, 0) + 1
n = n//i
if n > 2:
primes[n] = primes.get(n, 0) + 1
## prime factoriazation of n is stored in dictionary
## primes and can be accesed. O(sqrt n)
return primes
## MODULAR EXPONENTIATION FUNCTION
def power(x, y, p):
res = 1
x = x % p
if (x == 0) :
return 0
while (y > 0) :
if ((y & 1) == 1) :
res = (res * x) % p
y = y >> 1
x = (x * x) % p
return res
## DISJOINT SET UNINON FUNCTIONS
def swap(a,b):
temp = a
a = b
b = temp
return a,b
# find function with path compression included (recursive)
# def find(x, link):
# if link[x] == x:
# return x
# link[x] = find(link[x], link);
# return link[x];
# find function with path compression (ITERATIVE)
def find(x, link):
p = x;
while( p != link[p]):
p = link[p];
while( x != p):
nex = link[x];
link[x] = p;
x = nex;
return p;
# the union function which makes union(x,y)
# of two nodes x and y
def union(x, y, link, size):
x = find(x, link)
y = find(y, link)
if size[x] < size[y]:
x,y = swap(x,y)
if x != y:
size[x] += size[y]
link[y] = x
## returns an array of boolean if primes or not USING SIEVE OF ERATOSTHANES
def sieve(n):
prime = [True for i in range(n+1)]
p = 2
while (p * p <= n):
if (prime[p] == True):
for i in range(p * p, n+1, p):
prime[i] = False
p += 1
return prime
#### PRIME FACTORIZATION IN O(log n) using Sieve ####
MAXN = int(1e6 + 5)
def spf_sieve():
spf[1] = 1;
for i in range(2, MAXN):
spf[i] = i;
for i in range(4, MAXN, 2):
spf[i] = 2;
for i in range(3, ceil(MAXN ** 0.5), 2):
if spf[i] == i:
for j in range(i*i, MAXN, i):
if spf[j] == j:
spf[j] = i;
## function for storing smallest prime factors (spf) in the array
################## un-comment below 2 lines when using factorization #################
# spf = [0 for i in range(MAXN)]
# spf_sieve()
def factoriazation(x):
ret = {};
while x != 1:
ret[spf[x]] = ret.get(spf[x], 0) + 1;
x = x//spf[x]
return ret
## this function is useful for multiple queries only, o/w use
## primefs function above. complexity O(log n)
## taking integer array input
def int_array():
return list(map(int, input().strip().split()))
## taking string array input
def str_array():
return input().strip().split();
#defining a couple constants
MOD = int(1e9)+7;
CMOD = 998244353;
INF = float('inf'); NINF = -float('inf');
################### ---------------- TEMPLATE ENDS HERE ---------------- ###################
for _ in range(int(input())):
s = input().strip(); n = len(s);
zero = []; one = [];
z = o = 0;
for i in s:
if i == '1':
o += 1;
else:
z += 1;
zero.append(z); one.append(o);
ans = min(o, z);
for i in range(n):
a = one[i] + (z - zero[i]);
b = zero[i] + (o - one[i]);
ans = min(ans, a, b);
print(ans);
```
| 90,308 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Shubham has a binary string s. A binary string is a string containing only characters "0" and "1".
He can perform the following operation on the string any amount of times:
* Select an index of the string, and flip the character at that index. This means, if the character was "0", it becomes "1", and vice versa.
A string is called good if it does not contain "010" or "101" as a subsequence β for instance, "1001" contains "101" as a subsequence, hence it is not a good string, while "1000" doesn't contain neither "010" nor "101" as subsequences, so it is a good string.
What is the minimum number of operations he will have to perform, so that the string becomes good? It can be shown that with these operations we can make any string good.
A string a is a subsequence of a string b if a can be obtained from b by deletion of several (possibly, zero or all) characters.
Input
The first line of the input contains a single integer t (1β€ t β€ 100) β the number of test cases.
Each of the next t lines contains a binary string s (1 β€ |s| β€ 1000).
Output
For every string, output the minimum number of operations required to make it good.
Example
Input
7
001
100
101
010
0
1
001100
Output
0
0
1
1
0
0
2
Note
In test cases 1, 2, 5, 6 no operations are required since they are already good strings.
For the 3rd test case: "001" can be achieved by flipping the first character β and is one of the possible ways to get a good string.
For the 4th test case: "000" can be achieved by flipping the second character β and is one of the possible ways to get a good string.
For the 7th test case: "000000" can be achieved by flipping the third and fourth characters β and is one of the possible ways to get a good string.
Tags: implementation, strings
Correct Solution:
```
for _ in range(int(input())):
s = input()
ch0 = 0
ch1 = 0
ch = [[] for _ in range(1001)]
for i in range(len(s)):
ch[i] = [ch0, ch1]
if int(s[i]) == 0:
ch0 += 1
else:
ch1 += 1
ch[len(s)] = [ch0, ch1]
minn = []
for j in range(len(s) + 1):
now = ch[j]
c0 = now[0]
c1 = now[1]
minn.append(ch1 - c1 + c0)
minn.append(ch0 - c0 + c1)
print(min(minn))
```
| 90,309 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Shubham has a binary string s. A binary string is a string containing only characters "0" and "1".
He can perform the following operation on the string any amount of times:
* Select an index of the string, and flip the character at that index. This means, if the character was "0", it becomes "1", and vice versa.
A string is called good if it does not contain "010" or "101" as a subsequence β for instance, "1001" contains "101" as a subsequence, hence it is not a good string, while "1000" doesn't contain neither "010" nor "101" as subsequences, so it is a good string.
What is the minimum number of operations he will have to perform, so that the string becomes good? It can be shown that with these operations we can make any string good.
A string a is a subsequence of a string b if a can be obtained from b by deletion of several (possibly, zero or all) characters.
Input
The first line of the input contains a single integer t (1β€ t β€ 100) β the number of test cases.
Each of the next t lines contains a binary string s (1 β€ |s| β€ 1000).
Output
For every string, output the minimum number of operations required to make it good.
Example
Input
7
001
100
101
010
0
1
001100
Output
0
0
1
1
0
0
2
Note
In test cases 1, 2, 5, 6 no operations are required since they are already good strings.
For the 3rd test case: "001" can be achieved by flipping the first character β and is one of the possible ways to get a good string.
For the 4th test case: "000" can be achieved by flipping the second character β and is one of the possible ways to get a good string.
For the 7th test case: "000000" can be achieved by flipping the third and fourth characters β and is one of the possible ways to get a good string.
Tags: implementation, strings
Correct Solution:
```
class Solution:
def __init__(self):
self.s = input()
def solve_and_print(self):
right_1 = self.s.count('1')
left_0, left_1, right_0 = 0, 0, len(self.s)-right_1
min_op = len(self.s)
for c in self.s:
min_op = min(min_op, left_0+right_1, left_1+right_0)
if c == '1':
left_1 += 1
right_1 -= 1
else:
left_0 += 1
right_0 -= 1
print(min_op)
if __name__ == "__main__":
for _ in range(int(input())):
Solution().solve_and_print()
```
| 90,310 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Shubham has a binary string s. A binary string is a string containing only characters "0" and "1".
He can perform the following operation on the string any amount of times:
* Select an index of the string, and flip the character at that index. This means, if the character was "0", it becomes "1", and vice versa.
A string is called good if it does not contain "010" or "101" as a subsequence β for instance, "1001" contains "101" as a subsequence, hence it is not a good string, while "1000" doesn't contain neither "010" nor "101" as subsequences, so it is a good string.
What is the minimum number of operations he will have to perform, so that the string becomes good? It can be shown that with these operations we can make any string good.
A string a is a subsequence of a string b if a can be obtained from b by deletion of several (possibly, zero or all) characters.
Input
The first line of the input contains a single integer t (1β€ t β€ 100) β the number of test cases.
Each of the next t lines contains a binary string s (1 β€ |s| β€ 1000).
Output
For every string, output the minimum number of operations required to make it good.
Example
Input
7
001
100
101
010
0
1
001100
Output
0
0
1
1
0
0
2
Note
In test cases 1, 2, 5, 6 no operations are required since they are already good strings.
For the 3rd test case: "001" can be achieved by flipping the first character β and is one of the possible ways to get a good string.
For the 4th test case: "000" can be achieved by flipping the second character β and is one of the possible ways to get a good string.
For the 7th test case: "000000" can be achieved by flipping the third and fourth characters β and is one of the possible ways to get a good string.
Tags: implementation, strings
Correct Solution:
```
for _ in range(int(input())):
s=input()
sum=0
for i in s:
if i=='1':
sum+=1
if sum==0 or sum==len(s):
print(0)
else:
ans_now=100000000000000
l=0
r=sum
for i in range(len(s)):
if s[i]=='1':
l+=1
r-=1
ans_now=min(i+1-l+r,ans_now)
ans_now=min(l+len(s)-i-1-r,ans_now)
print(ans_now)
```
| 90,311 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Shubham has a binary string s. A binary string is a string containing only characters "0" and "1".
He can perform the following operation on the string any amount of times:
* Select an index of the string, and flip the character at that index. This means, if the character was "0", it becomes "1", and vice versa.
A string is called good if it does not contain "010" or "101" as a subsequence β for instance, "1001" contains "101" as a subsequence, hence it is not a good string, while "1000" doesn't contain neither "010" nor "101" as subsequences, so it is a good string.
What is the minimum number of operations he will have to perform, so that the string becomes good? It can be shown that with these operations we can make any string good.
A string a is a subsequence of a string b if a can be obtained from b by deletion of several (possibly, zero or all) characters.
Input
The first line of the input contains a single integer t (1β€ t β€ 100) β the number of test cases.
Each of the next t lines contains a binary string s (1 β€ |s| β€ 1000).
Output
For every string, output the minimum number of operations required to make it good.
Example
Input
7
001
100
101
010
0
1
001100
Output
0
0
1
1
0
0
2
Note
In test cases 1, 2, 5, 6 no operations are required since they are already good strings.
For the 3rd test case: "001" can be achieved by flipping the first character β and is one of the possible ways to get a good string.
For the 4th test case: "000" can be achieved by flipping the second character β and is one of the possible ways to get a good string.
For the 7th test case: "000000" can be achieved by flipping the third and fourth characters β and is one of the possible ways to get a good string.
Tags: implementation, strings
Correct Solution:
```
for _ in range(int(input())):
s = input()
ans = 10000000
total = 0
for i in s:
if i=='1':
total+=1
l = len(s)
ans = min(ans, total, l-total)
preZeroes = 0
for i in range(l):
if s[i]=='0':
preZeroes += 1
preOnes = i+1-preZeroes
postOnes = total - preOnes
postZeroes = l-i-1-postOnes
# print(postOnes,postZeroes,preZeroes,preOnes)
flip = min(preOnes+postZeroes, postOnes+preZeroes)
ans = min(ans, flip)
print(ans)
```
| 90,312 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Shubham has a binary string s. A binary string is a string containing only characters "0" and "1".
He can perform the following operation on the string any amount of times:
* Select an index of the string, and flip the character at that index. This means, if the character was "0", it becomes "1", and vice versa.
A string is called good if it does not contain "010" or "101" as a subsequence β for instance, "1001" contains "101" as a subsequence, hence it is not a good string, while "1000" doesn't contain neither "010" nor "101" as subsequences, so it is a good string.
What is the minimum number of operations he will have to perform, so that the string becomes good? It can be shown that with these operations we can make any string good.
A string a is a subsequence of a string b if a can be obtained from b by deletion of several (possibly, zero or all) characters.
Input
The first line of the input contains a single integer t (1β€ t β€ 100) β the number of test cases.
Each of the next t lines contains a binary string s (1 β€ |s| β€ 1000).
Output
For every string, output the minimum number of operations required to make it good.
Example
Input
7
001
100
101
010
0
1
001100
Output
0
0
1
1
0
0
2
Note
In test cases 1, 2, 5, 6 no operations are required since they are already good strings.
For the 3rd test case: "001" can be achieved by flipping the first character β and is one of the possible ways to get a good string.
For the 4th test case: "000" can be achieved by flipping the second character β and is one of the possible ways to get a good string.
For the 7th test case: "000000" can be achieved by flipping the third and fourth characters β and is one of the possible ways to get a good string.
Tags: implementation, strings
Correct Solution:
```
T=int(input())
for i in range(T):
s=input()
l=[]
ans=99999999999
n=len(s)
for i in range(n):
c=s[i]
ls=s[:i]
rs=s[i+1:]
lsz=ls.count("0")
lso=ls.count("1")
rsz=rs.count("0")
rso=rs.count("1")
ans=min(ans,lsz+rso,lso+rsz)
print(ans)
```
| 90,313 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Shubham has a binary string s. A binary string is a string containing only characters "0" and "1".
He can perform the following operation on the string any amount of times:
* Select an index of the string, and flip the character at that index. This means, if the character was "0", it becomes "1", and vice versa.
A string is called good if it does not contain "010" or "101" as a subsequence β for instance, "1001" contains "101" as a subsequence, hence it is not a good string, while "1000" doesn't contain neither "010" nor "101" as subsequences, so it is a good string.
What is the minimum number of operations he will have to perform, so that the string becomes good? It can be shown that with these operations we can make any string good.
A string a is a subsequence of a string b if a can be obtained from b by deletion of several (possibly, zero or all) characters.
Input
The first line of the input contains a single integer t (1β€ t β€ 100) β the number of test cases.
Each of the next t lines contains a binary string s (1 β€ |s| β€ 1000).
Output
For every string, output the minimum number of operations required to make it good.
Example
Input
7
001
100
101
010
0
1
001100
Output
0
0
1
1
0
0
2
Note
In test cases 1, 2, 5, 6 no operations are required since they are already good strings.
For the 3rd test case: "001" can be achieved by flipping the first character β and is one of the possible ways to get a good string.
For the 4th test case: "000" can be achieved by flipping the second character β and is one of the possible ways to get a good string.
For the 7th test case: "000000" can be achieved by flipping the third and fourth characters β and is one of the possible ways to get a good string.
Submitted Solution:
```
import sys, math
#from bisect import bisect_left as bl, bisect_right as br, insort
#from heapq import heapify, heappush, heappop
from collections import defaultdict as dd, deque, Counter
#from itertools import permutations,combinations
#from decimal import Decimal
def data(): return sys.stdin.readline().strip()
def mdata(): return list(map(int, data().split()))
def outl(var) : sys.stdout.write(' '.join(map(str, var))+'\n')
def out(var) : sys.stdout.write(str(var)+'\n')
sys.setrecursionlimit(100000)
INF = float('inf')
mod = int(1e9)+7
def main():
for t in range(int(data())):
s=data()
n=len(s)
dp1=[0]*n
dp2=[0]*n
for i in range(n):
if s[i]=='1':
dp1[i]=dp1[i-1]+1
dp2[i]=dp2[i-1]
else:
dp2[i] = dp2[i - 1] + 1
dp1[i] = dp1[i - 1]
m=dp1[-1]
for i in range(n):
m=min(m,dp1[i]+dp2[-1]-dp2[i],dp2[i]+dp1[-1]-dp1[i])
out(m)
if __name__ == '__main__':
main()
```
Yes
| 90,314 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Shubham has a binary string s. A binary string is a string containing only characters "0" and "1".
He can perform the following operation on the string any amount of times:
* Select an index of the string, and flip the character at that index. This means, if the character was "0", it becomes "1", and vice versa.
A string is called good if it does not contain "010" or "101" as a subsequence β for instance, "1001" contains "101" as a subsequence, hence it is not a good string, while "1000" doesn't contain neither "010" nor "101" as subsequences, so it is a good string.
What is the minimum number of operations he will have to perform, so that the string becomes good? It can be shown that with these operations we can make any string good.
A string a is a subsequence of a string b if a can be obtained from b by deletion of several (possibly, zero or all) characters.
Input
The first line of the input contains a single integer t (1β€ t β€ 100) β the number of test cases.
Each of the next t lines contains a binary string s (1 β€ |s| β€ 1000).
Output
For every string, output the minimum number of operations required to make it good.
Example
Input
7
001
100
101
010
0
1
001100
Output
0
0
1
1
0
0
2
Note
In test cases 1, 2, 5, 6 no operations are required since they are already good strings.
For the 3rd test case: "001" can be achieved by flipping the first character β and is one of the possible ways to get a good string.
For the 4th test case: "000" can be achieved by flipping the second character β and is one of the possible ways to get a good string.
For the 7th test case: "000000" can be achieved by flipping the third and fourth characters β and is one of the possible ways to get a good string.
Submitted Solution:
```
#qn given an arr of size n for every i position find a min j such that j>i and arr[j]>arr[i]
#it prints the position of the nearest .
import sys
input = sys.stdin.readline
#qn given an arr of size n for every i position find a min j such that j>i and arr[j]>arr[i]
#it prints the position of the nearest .
# import sys
import heapq
import copy
import math
import decimal
# from decimal import *
#heapq.heapify(li)
#
#heapq.heappush(li,4)
#
#heapq.heappop(li)
#
# & Bitwise AND Operator 10 & 7 = 2
# | Bitwise OR Operator 10 | 7 = 15
# ^ Bitwise XOR Operator 10 ^ 7 = 13
# << Bitwise Left Shift operator 10<<2 = 40
# >> Bitwise Right Shift Operator
# '''############ ---- Input Functions ---- #######Start#####'''
class Node:
def _init_(self,val):
self.data = val
self.left = None
self.right = None
##to initialize wire : object_name= node(val)##to create a new node
## can also be used to create linked list
class fen_tree:
"""Implementation of a Binary Indexed Tree (Fennwick Tree)"""
#def __init__(self, list):
# """Initialize BIT with list in O(n*log(n))"""
# self.array = [0] * (len(list) + 1)
# for idx, val in enumerate(list):
# self.update(idx, val)
def __init__(self, list):
""""Initialize BIT with list in O(n)"""
self.array = [0] + list
for idx in range(1, len(self.array)):
idx2 = idx + (idx & -idx)
if idx2 < len(self.array):
self.array[idx2] += self.array[idx]
def prefix_query(self, idx):
"""Computes prefix sum of up to including the idx-th element"""
# idx += 1
result = 0
while idx:
result += self.array[idx]
idx -= idx & -idx
return result
def prints(self):
print(self.array)
return
# for i in self.array:
# print(i,end = " ")
# return
def range_query(self, from_idx, to_idx):
"""Computes the range sum between two indices (both inclusive)"""
return self.prefix_query(to_idx) - self.prefix_query(from_idx - 1)
def update(self, idx, add):
"""Add a value to the idx-th element"""
# idx += 1
while idx < len(self.array):
self.array[idx] += add
idx += idx & -idx
def pre_sum(arr):
#"""returns the prefix sum inclusive ie ith position in ans represent sum from 0 to ith position"""
p = [0]
for i in arr:
p.append(p[-1] + i)
p.pop(0)
return p
def pre_back(arr):
#"""returns the prefix sum inclusive ie ith position in ans represent sum from 0 to ith position"""
p = [0]
for i in arr:
p.append(p[-1] + i)
p.pop(0)
return p
def bin_search(arr,l,r,val):#strickly greater
if arr[r] <= val:
return r+1
if r-l < 2:
if arr[l]>val:
return l
else:
return r
mid = int((l+r)/2)
if arr[mid] <= val:
return bin_search(arr,mid,r,val)
else:
return bin_search(arr,l,mid,val)
def search_leftmost(arr,val):
def helper(arr,l,r,val):
# print(arr)
print(l,r)
if arr[l] == val:
return l
if r -l <=1:
if arr[r] == val:
return r
else:
print("not found")
return
mid = int((r+l)/2)
if arr[mid] >= val:
return helper(arr,l,mid,val)
else:
return helper(arr,mid,r,val)
return helper(arr,0,len(arr)-1,val)
def search_rightmost(arr,val):
def helper(arr,l,r,val):
# print(arr)
print(l,r)
if arr[r] == val:
return r
if r -l <=1:
if arr[l] == val:
return r
else:
print("not found")
return
mid = int((r+l)/2)
if arr[mid] > val:
return helper(arr,l,mid,val)
else:
return helper(arr,mid,r,val)
return helper(arr,0,len(arr)-1,val)
def preorder_postorder(root,paths,parent,left,level):
# if len(paths[node]) ==1 and node !=1 :
# return [parent,left,level]
l = 0
queue = [root]
while(queue!=[]):
node = queue[-1]
# print(queue,node)
flag = 0
for i in paths[node]:
if i!=parent[node] and level[i]== sys.maxsize:
parent[i] = node
level[i] = level[node]+1
flag = 1
queue.append(i)
if flag == 0:
left[parent[node]] +=(1+left[node])
queue.pop()
# [parent,left,level] = helper(i,paths,parent,left,level)
# l = left[i] + l +1
# left[node] = l
return [parent,left,level]
def nCr(n, r, p):
# initialize numerator
# and denominator
if r == 0:
return 1
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 inp():
return(int(input()))
def inlt():
return(list(map(int,input().split())))
def insr():
s = input()
return(list(s[:len(s) - 1]))
def invr():
return(map(int,input().split()))
############ ---- Input Functions ---- #######End
# #####
def pr_list(a):
print(*a, sep=" ")
def main():
tests = inp()
# tests = 1
mod = 1000000007
limit = 10**18
for test in range(tests):
s = insr()
r = [0]
l= [0]
n = len(s)
for i in s:
if i == "0":
l.append(l[-1])
else:
l.append(l[-1]+1)
l.pop()
for i in range(n-1,-1,-1):
if s[i] == "0":
r.append(r[-1])
else:
r.append(r[-1]+1)
r.pop()
r.reverse()
# print(l,r)
ans = min(l[-1]+int(s[-1]), n - (l[-1]+int(s[-1])))
for i in range(0,n):
if i>0 or i < n-1:
l0 = l[i]
r1 = n-i-1 - r[i]
l1 = i-l[i]
r0 = r[i]
ans = min (ans,l0+r1,l1+r0)
elif i == 0:
ans = min (ans,r[0],n-r[0]-1)
else:
ans = min (ans,l[0],n-l[0]-1)
print(ans)
if __name__== "__main__":
main()
```
Yes
| 90,315 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Shubham has a binary string s. A binary string is a string containing only characters "0" and "1".
He can perform the following operation on the string any amount of times:
* Select an index of the string, and flip the character at that index. This means, if the character was "0", it becomes "1", and vice versa.
A string is called good if it does not contain "010" or "101" as a subsequence β for instance, "1001" contains "101" as a subsequence, hence it is not a good string, while "1000" doesn't contain neither "010" nor "101" as subsequences, so it is a good string.
What is the minimum number of operations he will have to perform, so that the string becomes good? It can be shown that with these operations we can make any string good.
A string a is a subsequence of a string b if a can be obtained from b by deletion of several (possibly, zero or all) characters.
Input
The first line of the input contains a single integer t (1β€ t β€ 100) β the number of test cases.
Each of the next t lines contains a binary string s (1 β€ |s| β€ 1000).
Output
For every string, output the minimum number of operations required to make it good.
Example
Input
7
001
100
101
010
0
1
001100
Output
0
0
1
1
0
0
2
Note
In test cases 1, 2, 5, 6 no operations are required since they are already good strings.
For the 3rd test case: "001" can be achieved by flipping the first character β and is one of the possible ways to get a good string.
For the 4th test case: "000" can be achieved by flipping the second character β and is one of the possible ways to get a good string.
For the 7th test case: "000000" can be achieved by flipping the third and fourth characters β and is one of the possible ways to get a good string.
Submitted Solution:
```
a = int(input())
for x in range(a):
c = input()
m = []
for y in range(0,len(c)):
f = 0
f += c[:y].count("1")
f += c[y:].count("0")
j = 0
j += c[:y].count("0")
j += c[y:].count("1")
m.append(f)
m.append(j)
print(min(m))
```
Yes
| 90,316 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Shubham has a binary string s. A binary string is a string containing only characters "0" and "1".
He can perform the following operation on the string any amount of times:
* Select an index of the string, and flip the character at that index. This means, if the character was "0", it becomes "1", and vice versa.
A string is called good if it does not contain "010" or "101" as a subsequence β for instance, "1001" contains "101" as a subsequence, hence it is not a good string, while "1000" doesn't contain neither "010" nor "101" as subsequences, so it is a good string.
What is the minimum number of operations he will have to perform, so that the string becomes good? It can be shown that with these operations we can make any string good.
A string a is a subsequence of a string b if a can be obtained from b by deletion of several (possibly, zero or all) characters.
Input
The first line of the input contains a single integer t (1β€ t β€ 100) β the number of test cases.
Each of the next t lines contains a binary string s (1 β€ |s| β€ 1000).
Output
For every string, output the minimum number of operations required to make it good.
Example
Input
7
001
100
101
010
0
1
001100
Output
0
0
1
1
0
0
2
Note
In test cases 1, 2, 5, 6 no operations are required since they are already good strings.
For the 3rd test case: "001" can be achieved by flipping the first character β and is one of the possible ways to get a good string.
For the 4th test case: "000" can be achieved by flipping the second character β and is one of the possible ways to get a good string.
For the 7th test case: "000000" can be achieved by flipping the third and fourth characters β and is one of the possible ways to get a good string.
Submitted Solution:
```
for _ in range(int(input())):
s = input()
n = len(s)
p = [0]
for c in s:
p.append((int(c) + p[-1]))
best = n
for i in range(1, n+1):
prez = p[i]
preo = i - prez
suffz = p[n] - p[i]
suffo = (n - i) - suffz
#print('i:', i, 'prez', prez, 'preo', preo, 'suffz', suffz, 'suffo', suffo)
#print('curr', i, prez + suffo, preo + suffz, prez + suffz, preo + suffo)
best = min(best, prez + suffo, preo + suffz, prez + suffz, preo + suffo)
print(best)
```
Yes
| 90,317 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Shubham has a binary string s. A binary string is a string containing only characters "0" and "1".
He can perform the following operation on the string any amount of times:
* Select an index of the string, and flip the character at that index. This means, if the character was "0", it becomes "1", and vice versa.
A string is called good if it does not contain "010" or "101" as a subsequence β for instance, "1001" contains "101" as a subsequence, hence it is not a good string, while "1000" doesn't contain neither "010" nor "101" as subsequences, so it is a good string.
What is the minimum number of operations he will have to perform, so that the string becomes good? It can be shown that with these operations we can make any string good.
A string a is a subsequence of a string b if a can be obtained from b by deletion of several (possibly, zero or all) characters.
Input
The first line of the input contains a single integer t (1β€ t β€ 100) β the number of test cases.
Each of the next t lines contains a binary string s (1 β€ |s| β€ 1000).
Output
For every string, output the minimum number of operations required to make it good.
Example
Input
7
001
100
101
010
0
1
001100
Output
0
0
1
1
0
0
2
Note
In test cases 1, 2, 5, 6 no operations are required since they are already good strings.
For the 3rd test case: "001" can be achieved by flipping the first character β and is one of the possible ways to get a good string.
For the 4th test case: "000" can be achieved by flipping the second character β and is one of the possible ways to get a good string.
For the 7th test case: "000000" can be achieved by flipping the third and fourth characters β and is one of the possible ways to get a good string.
Submitted Solution:
```
n=int(input())
l=[]
for i in range(n):
z=0
o=0
s=input()
for j in range(len(s)):
if s[j]=='0':
z+=1
else:
o+=1
if s[0]=='1' or s[-1]=='1':
o-=1
if o>z:
mini=z
else:
mini=o
l.append(mini)
for i in l:
print(i)
```
No
| 90,318 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Shubham has a binary string s. A binary string is a string containing only characters "0" and "1".
He can perform the following operation on the string any amount of times:
* Select an index of the string, and flip the character at that index. This means, if the character was "0", it becomes "1", and vice versa.
A string is called good if it does not contain "010" or "101" as a subsequence β for instance, "1001" contains "101" as a subsequence, hence it is not a good string, while "1000" doesn't contain neither "010" nor "101" as subsequences, so it is a good string.
What is the minimum number of operations he will have to perform, so that the string becomes good? It can be shown that with these operations we can make any string good.
A string a is a subsequence of a string b if a can be obtained from b by deletion of several (possibly, zero or all) characters.
Input
The first line of the input contains a single integer t (1β€ t β€ 100) β the number of test cases.
Each of the next t lines contains a binary string s (1 β€ |s| β€ 1000).
Output
For every string, output the minimum number of operations required to make it good.
Example
Input
7
001
100
101
010
0
1
001100
Output
0
0
1
1
0
0
2
Note
In test cases 1, 2, 5, 6 no operations are required since they are already good strings.
For the 3rd test case: "001" can be achieved by flipping the first character β and is one of the possible ways to get a good string.
For the 4th test case: "000" can be achieved by flipping the second character β and is one of the possible ways to get a good string.
For the 7th test case: "000000" can be achieved by flipping the third and fourth characters β and is one of the possible ways to get a good string.
Submitted Solution:
```
t=int(input())
for _ in range(t):
s=input()
if(len(s)<3):
print(0)
else:
t3=0
if(s[0]=='1'):
i=1
q=0
t2=1
while(i<len(s)):
if(s[i]=='0'):
q=1
else:
if(q==1):
t3+=t2
q=0
t2=1
else:
t2+=1
i+=1
else:
i=1
q=0
q1=0
t2=0
while(i<len(s)):
if(s[i]=='1'):
if(q1==1):
t3-=t2
break
else:
t2+=1
q=1
else:
if(q==1):
q1=1
t3+=t2
t2=0
i+=1
print(t3)
```
No
| 90,319 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Shubham has a binary string s. A binary string is a string containing only characters "0" and "1".
He can perform the following operation on the string any amount of times:
* Select an index of the string, and flip the character at that index. This means, if the character was "0", it becomes "1", and vice versa.
A string is called good if it does not contain "010" or "101" as a subsequence β for instance, "1001" contains "101" as a subsequence, hence it is not a good string, while "1000" doesn't contain neither "010" nor "101" as subsequences, so it is a good string.
What is the minimum number of operations he will have to perform, so that the string becomes good? It can be shown that with these operations we can make any string good.
A string a is a subsequence of a string b if a can be obtained from b by deletion of several (possibly, zero or all) characters.
Input
The first line of the input contains a single integer t (1β€ t β€ 100) β the number of test cases.
Each of the next t lines contains a binary string s (1 β€ |s| β€ 1000).
Output
For every string, output the minimum number of operations required to make it good.
Example
Input
7
001
100
101
010
0
1
001100
Output
0
0
1
1
0
0
2
Note
In test cases 1, 2, 5, 6 no operations are required since they are already good strings.
For the 3rd test case: "001" can be achieved by flipping the first character β and is one of the possible ways to get a good string.
For the 4th test case: "000" can be achieved by flipping the second character β and is one of the possible ways to get a good string.
For the 7th test case: "000000" can be achieved by flipping the third and fourth characters β and is one of the possible ways to get a good string.
Submitted Solution:
```
t=int(input())
for i in range(0,t):
s=input()
if len(s)<=2:
print(0)
else:
n=len(s)
p=s[0]
c1=0
c2=0
for j in range(0,len(s)):
if s[j]=='0':
c1+=1
else:
c2+=1
ans=min(c1,c2)
c=0
f=0
for j in range(1,n):
if s[j]!=p and f==0:
f=1
p=s[j]
elif s[j]!=p:
c+=1
ans=min(ans,c)
p=s[len(s)-1]
c=0
f=0
for j in range(n-1,-1,-1):
if s[j]!=p and f==0:
f=1
p=s[j]
elif s[j]!=p:
c+=1
ans=min(ans,c)
print(ans)
```
No
| 90,320 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Shubham has a binary string s. A binary string is a string containing only characters "0" and "1".
He can perform the following operation on the string any amount of times:
* Select an index of the string, and flip the character at that index. This means, if the character was "0", it becomes "1", and vice versa.
A string is called good if it does not contain "010" or "101" as a subsequence β for instance, "1001" contains "101" as a subsequence, hence it is not a good string, while "1000" doesn't contain neither "010" nor "101" as subsequences, so it is a good string.
What is the minimum number of operations he will have to perform, so that the string becomes good? It can be shown that with these operations we can make any string good.
A string a is a subsequence of a string b if a can be obtained from b by deletion of several (possibly, zero or all) characters.
Input
The first line of the input contains a single integer t (1β€ t β€ 100) β the number of test cases.
Each of the next t lines contains a binary string s (1 β€ |s| β€ 1000).
Output
For every string, output the minimum number of operations required to make it good.
Example
Input
7
001
100
101
010
0
1
001100
Output
0
0
1
1
0
0
2
Note
In test cases 1, 2, 5, 6 no operations are required since they are already good strings.
For the 3rd test case: "001" can be achieved by flipping the first character β and is one of the possible ways to get a good string.
For the 4th test case: "000" can be achieved by flipping the second character β and is one of the possible ways to get a good string.
For the 7th test case: "000000" can be achieved by flipping the third and fourth characters β and is one of the possible ways to get a good string.
Submitted Solution:
```
"""
~~ Author : Bhaskar
~~ Dated : 01~06~2020
"""
import sys
from bisect import *
from math import floor,sqrt,ceil,factorial as F,gcd,pi
from itertools import chain,combinations,permutations,accumulate
from collections import Counter,defaultdict,OrderedDict,deque
from array import array
INT_MAX = sys.maxsize
INT_MIN = -(sys.maxsize)-1
mod = 1000000007
ch = "abcdefghijklmnopqrstuvwxyz"
lcm = lambda a,b : (a*b)//gcd(a,b)
setbit = lambda x : bin(x)[2:].count("1")
def solve():
T = int(sys.stdin.readline())
for _ in range(T):
s = str(sys.stdin.readline()).replace('\n',"")
one = s.count("1")
zero = len(s)-one
if one == 0 or zero == 0:
print(0)
else:
if s[0] == s[-1] == "0":
print(s[1:-1].count("1"))
elif s[0] == s[-1] == "1":
print(s[1:-1].count("0"))
else:
if s[0] == "0" and s[-1] == "1":
grab = s[:-1]
print(min(grab.count("1"),grab.count("0")))
if s[0] == "1" and s[-1] == "0":
grab = s[1:]
print(min(grab.count("1"),grab.count("0")))
# print(one,zero)
if __name__ == "__main__":
try:
sys.stdin = open("input.txt","r")
except :
pass
solve()
```
No
| 90,321 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Koa the Koala has a matrix A of n rows and m columns. Elements of this matrix are distinct integers from 1 to n β
m (each number from 1 to n β
m appears exactly once in the matrix).
For any matrix M of n rows and m columns let's define the following:
* The i-th row of M is defined as R_i(M) = [ M_{i1}, M_{i2}, β¦, M_{im} ] for all i (1 β€ i β€ n).
* The j-th column of M is defined as C_j(M) = [ M_{1j}, M_{2j}, β¦, M_{nj} ] for all j (1 β€ j β€ m).
Koa defines S(A) = (X, Y) as the spectrum of A, where X is the set of the maximum values in rows of A and Y is the set of the maximum values in columns of A.
More formally:
* X = \{ max(R_1(A)), max(R_2(A)), β¦, max(R_n(A)) \}
* Y = \{ max(C_1(A)), max(C_2(A)), β¦, max(C_m(A)) \}
Koa asks you to find some matrix A' of n rows and m columns, such that each number from 1 to n β
m appears exactly once in the matrix, and the following conditions hold:
* S(A') = S(A)
* R_i(A') is bitonic for all i (1 β€ i β€ n)
* C_j(A') is bitonic for all j (1 β€ j β€ m)
An array t (t_1, t_2, β¦, t_k) is called bitonic if it first increases and then decreases.
More formally: t is bitonic if there exists some position p (1 β€ p β€ k) such that: t_1 < t_2 < β¦ < t_p > t_{p+1} > β¦ > t_k.
Help Koa to find such matrix or to determine that it doesn't exist.
Input
The first line of the input contains two integers n and m (1 β€ n, m β€ 250) β the number of rows and columns of A.
Each of the ollowing n lines contains m integers. The j-th integer in the i-th line denotes element A_{ij} (1 β€ A_{ij} β€ n β
m) of matrix A. It is guaranteed that every number from 1 to n β
m appears exactly once among elements of the matrix.
Output
If such matrix doesn't exist, print -1 on a single line.
Otherwise, the output must consist of n lines, each one consisting of m space separated integers β a description of A'.
The j-th number in the i-th line represents the element A'_{ij}.
Every integer from 1 to n β
m should appear exactly once in A', every row and column in A' must be bitonic and S(A) = S(A') must hold.
If there are many answers print any.
Examples
Input
3 3
3 5 6
1 7 9
4 8 2
Output
9 5 1
7 8 2
3 6 4
Input
2 2
4 1
3 2
Output
4 1
3 2
Input
3 4
12 10 8 6
3 4 5 7
2 11 9 1
Output
12 8 6 1
10 11 9 2
3 4 5 7
Note
Let's analyze the first sample:
For matrix A we have:
* Rows:
* R_1(A) = [3, 5, 6]; max(R_1(A)) = 6
* R_2(A) = [1, 7, 9]; max(R_2(A)) = 9
* R_3(A) = [4, 8, 2]; max(R_3(A)) = 8
* Columns:
* C_1(A) = [3, 1, 4]; max(C_1(A)) = 4
* C_2(A) = [5, 7, 8]; max(C_2(A)) = 8
* C_3(A) = [6, 9, 2]; max(C_3(A)) = 9
* X = \{ max(R_1(A)), max(R_2(A)), max(R_3(A)) \} = \{ 6, 9, 8 \}
* Y = \{ max(C_1(A)), max(C_2(A)), max(C_3(A)) \} = \{ 4, 8, 9 \}
* So S(A) = (X, Y) = (\{ 6, 9, 8 \}, \{ 4, 8, 9 \})
For matrix A' we have:
* Rows:
* R_1(A') = [9, 5, 1]; max(R_1(A')) = 9
* R_2(A') = [7, 8, 2]; max(R_2(A')) = 8
* R_3(A') = [3, 6, 4]; max(R_3(A')) = 6
* Columns:
* C_1(A') = [9, 7, 3]; max(C_1(A')) = 9
* C_2(A') = [5, 8, 6]; max(C_2(A')) = 8
* C_3(A') = [1, 2, 4]; max(C_3(A')) = 4
* Note that each of this arrays are bitonic.
* X = \{ max(R_1(A')), max(R_2(A')), max(R_3(A')) \} = \{ 9, 8, 6 \}
* Y = \{ max(C_1(A')), max(C_2(A')), max(C_3(A')) \} = \{ 9, 8, 4 \}
* So S(A') = (X, Y) = (\{ 9, 8, 6 \}, \{ 9, 8, 4 \})
Submitted Solution:
```
s=input()
n=input()
print(s.count(n))
```
No
| 90,322 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Koa the Koala has a matrix A of n rows and m columns. Elements of this matrix are distinct integers from 1 to n β
m (each number from 1 to n β
m appears exactly once in the matrix).
For any matrix M of n rows and m columns let's define the following:
* The i-th row of M is defined as R_i(M) = [ M_{i1}, M_{i2}, β¦, M_{im} ] for all i (1 β€ i β€ n).
* The j-th column of M is defined as C_j(M) = [ M_{1j}, M_{2j}, β¦, M_{nj} ] for all j (1 β€ j β€ m).
Koa defines S(A) = (X, Y) as the spectrum of A, where X is the set of the maximum values in rows of A and Y is the set of the maximum values in columns of A.
More formally:
* X = \{ max(R_1(A)), max(R_2(A)), β¦, max(R_n(A)) \}
* Y = \{ max(C_1(A)), max(C_2(A)), β¦, max(C_m(A)) \}
Koa asks you to find some matrix A' of n rows and m columns, such that each number from 1 to n β
m appears exactly once in the matrix, and the following conditions hold:
* S(A') = S(A)
* R_i(A') is bitonic for all i (1 β€ i β€ n)
* C_j(A') is bitonic for all j (1 β€ j β€ m)
An array t (t_1, t_2, β¦, t_k) is called bitonic if it first increases and then decreases.
More formally: t is bitonic if there exists some position p (1 β€ p β€ k) such that: t_1 < t_2 < β¦ < t_p > t_{p+1} > β¦ > t_k.
Help Koa to find such matrix or to determine that it doesn't exist.
Input
The first line of the input contains two integers n and m (1 β€ n, m β€ 250) β the number of rows and columns of A.
Each of the ollowing n lines contains m integers. The j-th integer in the i-th line denotes element A_{ij} (1 β€ A_{ij} β€ n β
m) of matrix A. It is guaranteed that every number from 1 to n β
m appears exactly once among elements of the matrix.
Output
If such matrix doesn't exist, print -1 on a single line.
Otherwise, the output must consist of n lines, each one consisting of m space separated integers β a description of A'.
The j-th number in the i-th line represents the element A'_{ij}.
Every integer from 1 to n β
m should appear exactly once in A', every row and column in A' must be bitonic and S(A) = S(A') must hold.
If there are many answers print any.
Examples
Input
3 3
3 5 6
1 7 9
4 8 2
Output
9 5 1
7 8 2
3 6 4
Input
2 2
4 1
3 2
Output
4 1
3 2
Input
3 4
12 10 8 6
3 4 5 7
2 11 9 1
Output
12 8 6 1
10 11 9 2
3 4 5 7
Note
Let's analyze the first sample:
For matrix A we have:
* Rows:
* R_1(A) = [3, 5, 6]; max(R_1(A)) = 6
* R_2(A) = [1, 7, 9]; max(R_2(A)) = 9
* R_3(A) = [4, 8, 2]; max(R_3(A)) = 8
* Columns:
* C_1(A) = [3, 1, 4]; max(C_1(A)) = 4
* C_2(A) = [5, 7, 8]; max(C_2(A)) = 8
* C_3(A) = [6, 9, 2]; max(C_3(A)) = 9
* X = \{ max(R_1(A)), max(R_2(A)), max(R_3(A)) \} = \{ 6, 9, 8 \}
* Y = \{ max(C_1(A)), max(C_2(A)), max(C_3(A)) \} = \{ 4, 8, 9 \}
* So S(A) = (X, Y) = (\{ 6, 9, 8 \}, \{ 4, 8, 9 \})
For matrix A' we have:
* Rows:
* R_1(A') = [9, 5, 1]; max(R_1(A')) = 9
* R_2(A') = [7, 8, 2]; max(R_2(A')) = 8
* R_3(A') = [3, 6, 4]; max(R_3(A')) = 6
* Columns:
* C_1(A') = [9, 7, 3]; max(C_1(A')) = 9
* C_2(A') = [5, 8, 6]; max(C_2(A')) = 8
* C_3(A') = [1, 2, 4]; max(C_3(A')) = 4
* Note that each of this arrays are bitonic.
* X = \{ max(R_1(A')), max(R_2(A')), max(R_3(A')) \} = \{ 9, 8, 6 \}
* Y = \{ max(C_1(A')), max(C_2(A')), max(C_3(A')) \} = \{ 9, 8, 4 \}
* So S(A') = (X, Y) = (\{ 9, 8, 6 \}, \{ 9, 8, 4 \})
Submitted Solution:
```
import sys
input = sys.stdin.readline
from operator import itemgetter
n,m=map(int,input().split())
A=[list(map(int,input().split())) for i in range(n)]
R=[]
for i in range(n):
R.append((max(A[i]),i))
R.sort(key=itemgetter(0))
A2=[]
for x,i in R:
A2.append(A[i])
C=[]
for i in range(m):
C.append((max([A2[j][i] for j in range(n)]),i))
C.sort(key=itemgetter(0))
A3=[[0]*m for i in range(n)]
for i in range(m):
x=C[i][1]
for j in range(n):
A3[j][i]=A2[j][x]
#print(A3)
for a in A3:
print(*a)
```
No
| 90,323 |
Provide tags and a correct Python 3 solution for this coding contest problem.
This is an interactive problem.
Consider a fixed positive integer n. Two players, First and Second play a game as follows:
1. First considers the 2n numbers 1, 2, ..., 2n, and partitions them as he wants into n disjoint pairs.
2. Then, Second chooses exactly one element from each of the pairs that First created (he chooses elements he wants).
To determine the winner of the game, we compute the sum of the numbers chosen by Second. If the sum of all these numbers is a multiple of 2n, then Second wins. Otherwise, First wins.
You are given the integer n. Your task is to decide which player you wish to play as and win the game.
Interaction
The interaction begins by reading the integer n (1 β€ n β€ 5 β
10^5).
After reading, print a single line containing either First or Second, denoting who you want to play as. The interaction then varies depending on who you chose to play as.
If you chose to play as First, print a single line containing 2n integers p_1, p_2, ..., p_{2n}, denoting that the number i belongs to the p_i-th pair for 1β€ i β€ 2n. Thus, 1 β€ p_i β€ n, and every number between 1 and n inclusive should appear exactly twice.
If you chose to play as Second, the interactor will print 2n integers p_1, p_2, ..., p_{2n}, denoting that the number i belongs to the p_i-th pair. As a response, print n integers a_1, a_2, ..., a_n in a single line. These should contain exactly one number from each pair.
Regardless of who you chose to play as the interactor will finish by printing a single integer: 0 if your answer for the test case is correct (that is, you are playing as First and it cannot choose adequate numbers from your pairs, or you are playing as Second and your chosen numbers add up to a multiple of 2n), or -1 if it is incorrect. In particular, the interactor will not print the chosen numbers if you choose to play First and lose. In either case, your program should terminate immediately after reading this number.
If at any point you make an invalid interaction, the interactor will print -1 and finish the interaction. You will receive a Wrong Answer verdict. Make sure to terminate immediately to avoid getting other verdicts.
After printing something do not forget to output end of line and flush the output. Otherwise, you will get Idleness limit exceeded. To do this, use:
* fflush(stdout) or cout.flush() in C++;
* System.out.flush() in Java;
* flush(output) in Pascal;
* stdout.flush() in Python;
* see documentation for other languages.
Hack Format
To hack, use the following format:
The first line contains an integer n (1 β€ n β€ 5 β
10^5).
The second line contains 2n integers p_1, p_2, ..., p_{2n}, denoting that the number i belongs to the p_i-th pair if the solution being hacked chooses to play as Second. If the solution being hacked chooses to play as First, those pairs don't matter but the p_1, p_2, ..., p_{2n} must still form a valid partition of 1, 2, ..., 2n into n disjoint pairs.
Examples
Input
2
1 1 2 2
0
Output
Second
1 3
Input
2
0
Output
First
2 1 2 1
Note
In the first sample, n = 2, and you decide to play as Second. The judge chooses the pairs (1, 2) and (3, 4), and you reply with the numbers 1 and 3. This is a valid choice since it contains exactly one number from each pair, and the sum 1 + 3 = 4 is divisible by 4.
In the second sample, n = 2 again, and you play as First. You choose the pairs (2, 4) and (1, 3). The judge fails to choose a number from each pair such that their sum is divisible by 4, so the answer is correct.
Note that the sample tests are just for illustration of the interaction protocol, and don't necessarily correspond to the behavior of the real interactor.
Tags: constructive algorithms, dfs and similar, interactive, math, number theory
Correct Solution:
```
import sys
n = int(input())
if n % 2:
print('Second')
sys.stdout.flush()
l = list(map(lambda x: int(x)-1,input().split()))
rev1 = [-1]*n
rev2 = [-1]*n
revs = [0]*n
for i in range(2 * n):
revs[l[i]] += i
if rev1[l[i]] == -1:
rev1[l[i]] = i
else:
rev2[l[i]] = i
out = [0] * (2 * n)
curr = 0
todo = 2*n
q = []
while todo:
while out[curr] and curr < 2*n:
curr += 1
if curr == 2*n:
break
out[curr] = 1
todo -= 1
q = [curr]
while q:
v = q.pop()
mod = v % n
other = (2 * mod + n) - v
if out[other] == 0:
out[other] = 3 - out[v]
todo -= 1
q.append(other)
other = revs[l[v]] - v
if out[other] == 0:
out[other] = 3 - out[v]
todo -= 1
q.append(other)
s1 = 0
for i in range(2 * n):
if out[i] == 1:
s1 += i + 1
if s1 % (2 * n) == 0:
want = 1
else:
want = 2
rout = []
for i in range(2 * n):
if out[i] == want:
rout.append(i + 1)
print(' '.join(map(str,rout)))
sys.stdout.flush()
else:
print('First')
sys.stdout.flush()
l = [1+(i%n) for i in range(2*n)]
print(' '.join(map(str,l)))
sys.stdout.flush()
```
| 90,324 |
Provide tags and a correct Python 3 solution for this coding contest problem.
This is an interactive problem.
Consider a fixed positive integer n. Two players, First and Second play a game as follows:
1. First considers the 2n numbers 1, 2, ..., 2n, and partitions them as he wants into n disjoint pairs.
2. Then, Second chooses exactly one element from each of the pairs that First created (he chooses elements he wants).
To determine the winner of the game, we compute the sum of the numbers chosen by Second. If the sum of all these numbers is a multiple of 2n, then Second wins. Otherwise, First wins.
You are given the integer n. Your task is to decide which player you wish to play as and win the game.
Interaction
The interaction begins by reading the integer n (1 β€ n β€ 5 β
10^5).
After reading, print a single line containing either First or Second, denoting who you want to play as. The interaction then varies depending on who you chose to play as.
If you chose to play as First, print a single line containing 2n integers p_1, p_2, ..., p_{2n}, denoting that the number i belongs to the p_i-th pair for 1β€ i β€ 2n. Thus, 1 β€ p_i β€ n, and every number between 1 and n inclusive should appear exactly twice.
If you chose to play as Second, the interactor will print 2n integers p_1, p_2, ..., p_{2n}, denoting that the number i belongs to the p_i-th pair. As a response, print n integers a_1, a_2, ..., a_n in a single line. These should contain exactly one number from each pair.
Regardless of who you chose to play as the interactor will finish by printing a single integer: 0 if your answer for the test case is correct (that is, you are playing as First and it cannot choose adequate numbers from your pairs, or you are playing as Second and your chosen numbers add up to a multiple of 2n), or -1 if it is incorrect. In particular, the interactor will not print the chosen numbers if you choose to play First and lose. In either case, your program should terminate immediately after reading this number.
If at any point you make an invalid interaction, the interactor will print -1 and finish the interaction. You will receive a Wrong Answer verdict. Make sure to terminate immediately to avoid getting other verdicts.
After printing something do not forget to output end of line and flush the output. Otherwise, you will get Idleness limit exceeded. To do this, use:
* fflush(stdout) or cout.flush() in C++;
* System.out.flush() in Java;
* flush(output) in Pascal;
* stdout.flush() in Python;
* see documentation for other languages.
Hack Format
To hack, use the following format:
The first line contains an integer n (1 β€ n β€ 5 β
10^5).
The second line contains 2n integers p_1, p_2, ..., p_{2n}, denoting that the number i belongs to the p_i-th pair if the solution being hacked chooses to play as Second. If the solution being hacked chooses to play as First, those pairs don't matter but the p_1, p_2, ..., p_{2n} must still form a valid partition of 1, 2, ..., 2n into n disjoint pairs.
Examples
Input
2
1 1 2 2
0
Output
Second
1 3
Input
2
0
Output
First
2 1 2 1
Note
In the first sample, n = 2, and you decide to play as Second. The judge chooses the pairs (1, 2) and (3, 4), and you reply with the numbers 1 and 3. This is a valid choice since it contains exactly one number from each pair, and the sum 1 + 3 = 4 is divisible by 4.
In the second sample, n = 2 again, and you play as First. You choose the pairs (2, 4) and (1, 3). The judge fails to choose a number from each pair such that their sum is divisible by 4, so the answer is correct.
Note that the sample tests are just for illustration of the interaction protocol, and don't necessarily correspond to the behavior of the real interactor.
Tags: constructive algorithms, dfs and similar, interactive, math, number theory
Correct Solution:
```
import sys;n = int(input())
if n % 2:
print('Second');sys.stdout.flush();l = list(map(lambda x: int(x)-1,input().split()));rev1,rev2,revs = [-1]*n,[-1]*n,[0]*n;out = [0] * (2 * n);curr,todo,q,s1,rout = 0,2*n,[],0,[]
for i in range(2 * n):
revs[l[i]] += i
if rev1[l[i]] == -1:rev1[l[i]] = i
else:rev2[l[i]] = i
while todo:
while out[curr] and curr < 2*n:curr += 1
if curr == 2*n:break
out[curr] = 1;todo -= 1;q = [curr]
while q:
v = q.pop();mod = v % n;other = (2 * mod + n) - v
if out[other] == 0:out[other] = 3 - out[v];todo -= 1;q.append(other)
other = revs[l[v]] - v
if out[other] == 0:out[other] = 3 - out[v];todo -= 1;q.append(other)
for i in range(2 * n):
if out[i] == 1:s1 += i + 1
if s1 % (2 * n) == 0:want = 1
else:want = 2
for i in range(2 * n):
if out[i] == want:rout.append(i + 1)
print(' '.join(map(str,rout)));sys.stdout.flush()
else:print('First');sys.stdout.flush();l = [1+(i%n) for i in range(2*n)];print(' '.join(map(str,l)));sys.stdout.flush()
```
| 90,325 |
Provide tags and a correct Python 3 solution for this coding contest problem.
This is an interactive problem.
Consider a fixed positive integer n. Two players, First and Second play a game as follows:
1. First considers the 2n numbers 1, 2, ..., 2n, and partitions them as he wants into n disjoint pairs.
2. Then, Second chooses exactly one element from each of the pairs that First created (he chooses elements he wants).
To determine the winner of the game, we compute the sum of the numbers chosen by Second. If the sum of all these numbers is a multiple of 2n, then Second wins. Otherwise, First wins.
You are given the integer n. Your task is to decide which player you wish to play as and win the game.
Interaction
The interaction begins by reading the integer n (1 β€ n β€ 5 β
10^5).
After reading, print a single line containing either First or Second, denoting who you want to play as. The interaction then varies depending on who you chose to play as.
If you chose to play as First, print a single line containing 2n integers p_1, p_2, ..., p_{2n}, denoting that the number i belongs to the p_i-th pair for 1β€ i β€ 2n. Thus, 1 β€ p_i β€ n, and every number between 1 and n inclusive should appear exactly twice.
If you chose to play as Second, the interactor will print 2n integers p_1, p_2, ..., p_{2n}, denoting that the number i belongs to the p_i-th pair. As a response, print n integers a_1, a_2, ..., a_n in a single line. These should contain exactly one number from each pair.
Regardless of who you chose to play as the interactor will finish by printing a single integer: 0 if your answer for the test case is correct (that is, you are playing as First and it cannot choose adequate numbers from your pairs, or you are playing as Second and your chosen numbers add up to a multiple of 2n), or -1 if it is incorrect. In particular, the interactor will not print the chosen numbers if you choose to play First and lose. In either case, your program should terminate immediately after reading this number.
If at any point you make an invalid interaction, the interactor will print -1 and finish the interaction. You will receive a Wrong Answer verdict. Make sure to terminate immediately to avoid getting other verdicts.
After printing something do not forget to output end of line and flush the output. Otherwise, you will get Idleness limit exceeded. To do this, use:
* fflush(stdout) or cout.flush() in C++;
* System.out.flush() in Java;
* flush(output) in Pascal;
* stdout.flush() in Python;
* see documentation for other languages.
Hack Format
To hack, use the following format:
The first line contains an integer n (1 β€ n β€ 5 β
10^5).
The second line contains 2n integers p_1, p_2, ..., p_{2n}, denoting that the number i belongs to the p_i-th pair if the solution being hacked chooses to play as Second. If the solution being hacked chooses to play as First, those pairs don't matter but the p_1, p_2, ..., p_{2n} must still form a valid partition of 1, 2, ..., 2n into n disjoint pairs.
Examples
Input
2
1 1 2 2
0
Output
Second
1 3
Input
2
0
Output
First
2 1 2 1
Note
In the first sample, n = 2, and you decide to play as Second. The judge chooses the pairs (1, 2) and (3, 4), and you reply with the numbers 1 and 3. This is a valid choice since it contains exactly one number from each pair, and the sum 1 + 3 = 4 is divisible by 4.
In the second sample, n = 2 again, and you play as First. You choose the pairs (2, 4) and (1, 3). The judge fails to choose a number from each pair such that their sum is divisible by 4, so the answer is correct.
Note that the sample tests are just for illustration of the interaction protocol, and don't necessarily correspond to the behavior of the real interactor.
Tags: constructive algorithms, dfs and similar, interactive, math, number theory
Correct Solution:
```
# Fast IO (be careful about bytestring)
# import os,io
# input=io.BytesIO(os.read(0,os.fstat(0).st_size)).readline
import sys
n = int(input())
if n % 2 == 0:
print("First")
sys.stdout.flush()
ans = []
for i in range(n):
ans.append(str(i+1))
for i in range(n):
ans.append(str(i+1))
print(" ".join(ans))
sys.stdout.flush()
else:
print("Second")
sys.stdout.flush()
p = list(map(int,input().split()))
inverseP = []
for i in range(n):
inverseP.append([])
for i in range(2 * n):
inverseP[p[i]-1].append(i)
for i in range(2 * n):
p[i] -= 1
chosenElement = []
consideredList = [False] * (2 * n)
cnt = 0
while len(chosenElement) < n:
while consideredList[inverseP[cnt][0]]:
cnt += 1
if cnt >= n:
break
currentElement = inverseP[cnt][0]
while True:
if consideredList[currentElement]:
break
chosenElement.append(currentElement + 1)
consideredList[currentElement] = True
consideredList[(currentElement + n) % (n * 2)] = True
curP = p[(currentElement + n) % (n * 2)]
if (currentElement + n) % (n * 2) == inverseP[curP][0]:
currentElement = inverseP[curP][1]
else:
currentElement = inverseP[curP][0]
if sum(chosenElement) % (2 * n) == 0:
print(" ".join(map(str,chosenElement)))
else:
isChosen = [False] * (2 * n)
for elem in chosenElement:
isChosen[elem - 1] = True
ans = []
for i in range(2 * n):
if isChosen[i] == False:
ans.append(str(i + 1))
print(" ".join(ans))
```
| 90,326 |
Provide tags and a correct Python 3 solution for this coding contest problem.
This is an interactive problem.
Consider a fixed positive integer n. Two players, First and Second play a game as follows:
1. First considers the 2n numbers 1, 2, ..., 2n, and partitions them as he wants into n disjoint pairs.
2. Then, Second chooses exactly one element from each of the pairs that First created (he chooses elements he wants).
To determine the winner of the game, we compute the sum of the numbers chosen by Second. If the sum of all these numbers is a multiple of 2n, then Second wins. Otherwise, First wins.
You are given the integer n. Your task is to decide which player you wish to play as and win the game.
Interaction
The interaction begins by reading the integer n (1 β€ n β€ 5 β
10^5).
After reading, print a single line containing either First or Second, denoting who you want to play as. The interaction then varies depending on who you chose to play as.
If you chose to play as First, print a single line containing 2n integers p_1, p_2, ..., p_{2n}, denoting that the number i belongs to the p_i-th pair for 1β€ i β€ 2n. Thus, 1 β€ p_i β€ n, and every number between 1 and n inclusive should appear exactly twice.
If you chose to play as Second, the interactor will print 2n integers p_1, p_2, ..., p_{2n}, denoting that the number i belongs to the p_i-th pair. As a response, print n integers a_1, a_2, ..., a_n in a single line. These should contain exactly one number from each pair.
Regardless of who you chose to play as the interactor will finish by printing a single integer: 0 if your answer for the test case is correct (that is, you are playing as First and it cannot choose adequate numbers from your pairs, or you are playing as Second and your chosen numbers add up to a multiple of 2n), or -1 if it is incorrect. In particular, the interactor will not print the chosen numbers if you choose to play First and lose. In either case, your program should terminate immediately after reading this number.
If at any point you make an invalid interaction, the interactor will print -1 and finish the interaction. You will receive a Wrong Answer verdict. Make sure to terminate immediately to avoid getting other verdicts.
After printing something do not forget to output end of line and flush the output. Otherwise, you will get Idleness limit exceeded. To do this, use:
* fflush(stdout) or cout.flush() in C++;
* System.out.flush() in Java;
* flush(output) in Pascal;
* stdout.flush() in Python;
* see documentation for other languages.
Hack Format
To hack, use the following format:
The first line contains an integer n (1 β€ n β€ 5 β
10^5).
The second line contains 2n integers p_1, p_2, ..., p_{2n}, denoting that the number i belongs to the p_i-th pair if the solution being hacked chooses to play as Second. If the solution being hacked chooses to play as First, those pairs don't matter but the p_1, p_2, ..., p_{2n} must still form a valid partition of 1, 2, ..., 2n into n disjoint pairs.
Examples
Input
2
1 1 2 2
0
Output
Second
1 3
Input
2
0
Output
First
2 1 2 1
Note
In the first sample, n = 2, and you decide to play as Second. The judge chooses the pairs (1, 2) and (3, 4), and you reply with the numbers 1 and 3. This is a valid choice since it contains exactly one number from each pair, and the sum 1 + 3 = 4 is divisible by 4.
In the second sample, n = 2 again, and you play as First. You choose the pairs (2, 4) and (1, 3). The judge fails to choose a number from each pair such that their sum is divisible by 4, so the answer is correct.
Note that the sample tests are just for illustration of the interaction protocol, and don't necessarily correspond to the behavior of the real interactor.
Tags: constructive algorithms, dfs and similar, interactive, math, number theory
Correct Solution:
```
import sys
n = int(input())
if n % 2:
print('Second')
sys.stdout.flush()
l = list(map(lambda x: int(x)-1,input().split()))
rev1 = [-1]*n
rev2 = [-1]*n
revs = [0]*n
for i in range(2 * n):
revs[l[i]] += i
if rev1[l[i]] == -1:rev1[l[i]] = i
else:rev2[l[i]] = i
out = [0] * (2 * n)
curr = 0
todo = 2*n
q = []
while todo:
while out[curr] and curr < 2*n:curr += 1
if curr == 2*n:break
out[curr] = 1;todo -= 1;q = [curr]
while q:
v = q.pop();mod = v % n;other = (2 * mod + n) - v
if out[other] == 0:out[other] = 3 - out[v];todo -= 1;q.append(other)
other = revs[l[v]] - v
if out[other] == 0:out[other] = 3 - out[v];todo -= 1;q.append(other)
s1 = 0;rout = []
for i in range(2 * n):
if out[i] == 1:s1 += i + 1
if s1 % (2 * n) == 0:want = 1
else:want = 2
for i in range(2 * n):
if out[i] == want:rout.append(i + 1)
print(' '.join(map(str,rout)));sys.stdout.flush()
else:print('First');sys.stdout.flush();l = [1+(i%n) for i in range(2*n)];print(' '.join(map(str,l)));sys.stdout.flush()
```
| 90,327 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
This is an interactive problem.
Consider a fixed positive integer n. Two players, First and Second play a game as follows:
1. First considers the 2n numbers 1, 2, ..., 2n, and partitions them as he wants into n disjoint pairs.
2. Then, Second chooses exactly one element from each of the pairs that First created (he chooses elements he wants).
To determine the winner of the game, we compute the sum of the numbers chosen by Second. If the sum of all these numbers is a multiple of 2n, then Second wins. Otherwise, First wins.
You are given the integer n. Your task is to decide which player you wish to play as and win the game.
Interaction
The interaction begins by reading the integer n (1 β€ n β€ 5 β
10^5).
After reading, print a single line containing either First or Second, denoting who you want to play as. The interaction then varies depending on who you chose to play as.
If you chose to play as First, print a single line containing 2n integers p_1, p_2, ..., p_{2n}, denoting that the number i belongs to the p_i-th pair for 1β€ i β€ 2n. Thus, 1 β€ p_i β€ n, and every number between 1 and n inclusive should appear exactly twice.
If you chose to play as Second, the interactor will print 2n integers p_1, p_2, ..., p_{2n}, denoting that the number i belongs to the p_i-th pair. As a response, print n integers a_1, a_2, ..., a_n in a single line. These should contain exactly one number from each pair.
Regardless of who you chose to play as the interactor will finish by printing a single integer: 0 if your answer for the test case is correct (that is, you are playing as First and it cannot choose adequate numbers from your pairs, or you are playing as Second and your chosen numbers add up to a multiple of 2n), or -1 if it is incorrect. In particular, the interactor will not print the chosen numbers if you choose to play First and lose. In either case, your program should terminate immediately after reading this number.
If at any point you make an invalid interaction, the interactor will print -1 and finish the interaction. You will receive a Wrong Answer verdict. Make sure to terminate immediately to avoid getting other verdicts.
After printing something do not forget to output end of line and flush the output. Otherwise, you will get Idleness limit exceeded. To do this, use:
* fflush(stdout) or cout.flush() in C++;
* System.out.flush() in Java;
* flush(output) in Pascal;
* stdout.flush() in Python;
* see documentation for other languages.
Hack Format
To hack, use the following format:
The first line contains an integer n (1 β€ n β€ 5 β
10^5).
The second line contains 2n integers p_1, p_2, ..., p_{2n}, denoting that the number i belongs to the p_i-th pair if the solution being hacked chooses to play as Second. If the solution being hacked chooses to play as First, those pairs don't matter but the p_1, p_2, ..., p_{2n} must still form a valid partition of 1, 2, ..., 2n into n disjoint pairs.
Examples
Input
2
1 1 2 2
0
Output
Second
1 3
Input
2
0
Output
First
2 1 2 1
Note
In the first sample, n = 2, and you decide to play as Second. The judge chooses the pairs (1, 2) and (3, 4), and you reply with the numbers 1 and 3. This is a valid choice since it contains exactly one number from each pair, and the sum 1 + 3 = 4 is divisible by 4.
In the second sample, n = 2 again, and you play as First. You choose the pairs (2, 4) and (1, 3). The judge fails to choose a number from each pair such that their sum is divisible by 4, so the answer is correct.
Note that the sample tests are just for illustration of the interaction protocol, and don't necessarily correspond to the behavior of the real interactor.
Submitted Solution:
```
import sys
import random
n = int(input())
sys.stdout.flush()
if n%4 == 2:
print("First")
sys.stdout.flush()
odp = []
for i in range(2*n):
if i % 4 == 0:
odp.append(i//2 + 1)
if i % 4 == 1:
odp.append(i//2 + 2)
if i % 4 == 2:
odp.append(i//2)
if i % 4 == 3:
odp.append(i//2 + 1)
print(*odp)
u = int(input())
sys.stdout.flush()
sys.exit(0)
elif n%4 == 0:
print("First")
sys.stdout.flush()
odp = list(range(1,n+1)) + list(range(1,n+1))
print(*odp)
u = int(input())
sys.stdout.flush()
sys.exit(0)
else:
print("Second")
sys.stdout.flush()
pary = [[] for i in range(n)]
l = list(map(int,input().split()))
for i in range(2*n):
pary[l[i]-1].append(i + 1)
moje = [0 for i in range(n)]
a = 0
for i in range(n):
a += pary[i][0]
while a%(2*n) != 0:
x = random.randint(0,n)
moje[x] = (moje[x]+1)%2
a += pary[x][moje[x]]
a -= pary[x][(moje[x]-1)%2]
odp = [pary[i][moje[i]] for i in range(n)]
print(sum(odp)%n)
print(*odp)
sys.stdout.flush()
u = int(input())
sys.stdout.flush()
sys.exit(0)
```
No
| 90,328 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
This is an interactive problem.
Consider a fixed positive integer n. Two players, First and Second play a game as follows:
1. First considers the 2n numbers 1, 2, ..., 2n, and partitions them as he wants into n disjoint pairs.
2. Then, Second chooses exactly one element from each of the pairs that First created (he chooses elements he wants).
To determine the winner of the game, we compute the sum of the numbers chosen by Second. If the sum of all these numbers is a multiple of 2n, then Second wins. Otherwise, First wins.
You are given the integer n. Your task is to decide which player you wish to play as and win the game.
Interaction
The interaction begins by reading the integer n (1 β€ n β€ 5 β
10^5).
After reading, print a single line containing either First or Second, denoting who you want to play as. The interaction then varies depending on who you chose to play as.
If you chose to play as First, print a single line containing 2n integers p_1, p_2, ..., p_{2n}, denoting that the number i belongs to the p_i-th pair for 1β€ i β€ 2n. Thus, 1 β€ p_i β€ n, and every number between 1 and n inclusive should appear exactly twice.
If you chose to play as Second, the interactor will print 2n integers p_1, p_2, ..., p_{2n}, denoting that the number i belongs to the p_i-th pair. As a response, print n integers a_1, a_2, ..., a_n in a single line. These should contain exactly one number from each pair.
Regardless of who you chose to play as the interactor will finish by printing a single integer: 0 if your answer for the test case is correct (that is, you are playing as First and it cannot choose adequate numbers from your pairs, or you are playing as Second and your chosen numbers add up to a multiple of 2n), or -1 if it is incorrect. In particular, the interactor will not print the chosen numbers if you choose to play First and lose. In either case, your program should terminate immediately after reading this number.
If at any point you make an invalid interaction, the interactor will print -1 and finish the interaction. You will receive a Wrong Answer verdict. Make sure to terminate immediately to avoid getting other verdicts.
After printing something do not forget to output end of line and flush the output. Otherwise, you will get Idleness limit exceeded. To do this, use:
* fflush(stdout) or cout.flush() in C++;
* System.out.flush() in Java;
* flush(output) in Pascal;
* stdout.flush() in Python;
* see documentation for other languages.
Hack Format
To hack, use the following format:
The first line contains an integer n (1 β€ n β€ 5 β
10^5).
The second line contains 2n integers p_1, p_2, ..., p_{2n}, denoting that the number i belongs to the p_i-th pair if the solution being hacked chooses to play as Second. If the solution being hacked chooses to play as First, those pairs don't matter but the p_1, p_2, ..., p_{2n} must still form a valid partition of 1, 2, ..., 2n into n disjoint pairs.
Examples
Input
2
1 1 2 2
0
Output
Second
1 3
Input
2
0
Output
First
2 1 2 1
Note
In the first sample, n = 2, and you decide to play as Second. The judge chooses the pairs (1, 2) and (3, 4), and you reply with the numbers 1 and 3. This is a valid choice since it contains exactly one number from each pair, and the sum 1 + 3 = 4 is divisible by 4.
In the second sample, n = 2 again, and you play as First. You choose the pairs (2, 4) and (1, 3). The judge fails to choose a number from each pair such that their sum is divisible by 4, so the answer is correct.
Note that the sample tests are just for illustration of the interaction protocol, and don't necessarily correspond to the behavior of the real interactor.
Submitted Solution:
```
import sys
import random
n = int(input())
sys.stdout.flush()
if n%4 == 2:
print("First")
sys.stdout.flush()
odp = []
for i in range(2*n):
if i % 4 == 0:
odp.append(i//2 + 1)
if i % 4 == 1:
odp.append(i//2 + 2)
if i % 4 == 2:
odp.append(i//2)
if i % 4 == 3:
odp.append(i//2 + 1)
print(*odp)
u = int(input())
sys.stdout.flush()
sys.exit(0)
if n%4 == 0:
print("First")
sys.stdout.flush()
odp = list(range(1,n+1)) + list(range(1,n+1))
print(*odp)
u = int(input())
sys.stdout.flush()
sys.exit(0)
else:
print("Second")
sys.stdout.flush()
pary = [[] for i in range(n)]
l = list(map(int,input().split()))
for i in range(2*n):
pary[l[i]-1].append(i + 1)
moje = [0 for i in range(n)]
a = 0
for i in range(n):
a += pary[i][0]
while a%n != 0:
x = random.randint(0,n-1)
moje[x] = (moje[x]+1)%2
a += pary[x][moje[x]]
a -= pary[x][(moje[x]-1)%2]
odp = [pary[i][moje[i]] for i in range(n)]
print(*odp)
sys.stdout.flush()
u = int(input())
sys.stdout.flush()
sys.exit(0)
```
No
| 90,329 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
This is an interactive problem.
Consider a fixed positive integer n. Two players, First and Second play a game as follows:
1. First considers the 2n numbers 1, 2, ..., 2n, and partitions them as he wants into n disjoint pairs.
2. Then, Second chooses exactly one element from each of the pairs that First created (he chooses elements he wants).
To determine the winner of the game, we compute the sum of the numbers chosen by Second. If the sum of all these numbers is a multiple of 2n, then Second wins. Otherwise, First wins.
You are given the integer n. Your task is to decide which player you wish to play as and win the game.
Interaction
The interaction begins by reading the integer n (1 β€ n β€ 5 β
10^5).
After reading, print a single line containing either First or Second, denoting who you want to play as. The interaction then varies depending on who you chose to play as.
If you chose to play as First, print a single line containing 2n integers p_1, p_2, ..., p_{2n}, denoting that the number i belongs to the p_i-th pair for 1β€ i β€ 2n. Thus, 1 β€ p_i β€ n, and every number between 1 and n inclusive should appear exactly twice.
If you chose to play as Second, the interactor will print 2n integers p_1, p_2, ..., p_{2n}, denoting that the number i belongs to the p_i-th pair. As a response, print n integers a_1, a_2, ..., a_n in a single line. These should contain exactly one number from each pair.
Regardless of who you chose to play as the interactor will finish by printing a single integer: 0 if your answer for the test case is correct (that is, you are playing as First and it cannot choose adequate numbers from your pairs, or you are playing as Second and your chosen numbers add up to a multiple of 2n), or -1 if it is incorrect. In particular, the interactor will not print the chosen numbers if you choose to play First and lose. In either case, your program should terminate immediately after reading this number.
If at any point you make an invalid interaction, the interactor will print -1 and finish the interaction. You will receive a Wrong Answer verdict. Make sure to terminate immediately to avoid getting other verdicts.
After printing something do not forget to output end of line and flush the output. Otherwise, you will get Idleness limit exceeded. To do this, use:
* fflush(stdout) or cout.flush() in C++;
* System.out.flush() in Java;
* flush(output) in Pascal;
* stdout.flush() in Python;
* see documentation for other languages.
Hack Format
To hack, use the following format:
The first line contains an integer n (1 β€ n β€ 5 β
10^5).
The second line contains 2n integers p_1, p_2, ..., p_{2n}, denoting that the number i belongs to the p_i-th pair if the solution being hacked chooses to play as Second. If the solution being hacked chooses to play as First, those pairs don't matter but the p_1, p_2, ..., p_{2n} must still form a valid partition of 1, 2, ..., 2n into n disjoint pairs.
Examples
Input
2
1 1 2 2
0
Output
Second
1 3
Input
2
0
Output
First
2 1 2 1
Note
In the first sample, n = 2, and you decide to play as Second. The judge chooses the pairs (1, 2) and (3, 4), and you reply with the numbers 1 and 3. This is a valid choice since it contains exactly one number from each pair, and the sum 1 + 3 = 4 is divisible by 4.
In the second sample, n = 2 again, and you play as First. You choose the pairs (2, 4) and (1, 3). The judge fails to choose a number from each pair such that their sum is divisible by 4, so the answer is correct.
Note that the sample tests are just for illustration of the interaction protocol, and don't necessarily correspond to the behavior of the real interactor.
Submitted Solution:
```
import sys
import random
n = int(input())
sys.stdout.flush()
if n%4 == 2:
print("First")
sys.stdout.flush()
odp = []
for i in range(2*n):
if i % 4 == 0:
odp.append(i//2 + 1)
if i % 4 == 1:
odp.append(i//2 + 2)
if i % 4 == 2:
odp.append(i//2)
if i % 4 == 3:
odp.append(i//2 + 1)
print(*odp)
u = int(input())
sys.stdout.flush()
sys.exit(0)
else:
print("Second")
sys.stdout.flush()
pary = [[] for i in range(n)]
l = list(map(int,input().split()))
for i in range(2*n):
pary[l[i]-1].append(i + 1)
moje = [0 for i in range(n)]
a = 0
for i in range(n):
a += pary[i][0]
while a%n != 0:
x = random.randint(0,n-1)
moje[x] = (moje[x]+1)%2
a += pary[x][moje[x]]
a -= pary[x][(moje[x]-1)%2]
odp = [pary[i][moje[i]] for i in range(n)]
print(*odp)
sys.stdout.flush()
u = int(input())
sys.stdout.flush()
sys.exit(0)
```
No
| 90,330 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
This is an interactive problem.
Consider a fixed positive integer n. Two players, First and Second play a game as follows:
1. First considers the 2n numbers 1, 2, ..., 2n, and partitions them as he wants into n disjoint pairs.
2. Then, Second chooses exactly one element from each of the pairs that First created (he chooses elements he wants).
To determine the winner of the game, we compute the sum of the numbers chosen by Second. If the sum of all these numbers is a multiple of 2n, then Second wins. Otherwise, First wins.
You are given the integer n. Your task is to decide which player you wish to play as and win the game.
Interaction
The interaction begins by reading the integer n (1 β€ n β€ 5 β
10^5).
After reading, print a single line containing either First or Second, denoting who you want to play as. The interaction then varies depending on who you chose to play as.
If you chose to play as First, print a single line containing 2n integers p_1, p_2, ..., p_{2n}, denoting that the number i belongs to the p_i-th pair for 1β€ i β€ 2n. Thus, 1 β€ p_i β€ n, and every number between 1 and n inclusive should appear exactly twice.
If you chose to play as Second, the interactor will print 2n integers p_1, p_2, ..., p_{2n}, denoting that the number i belongs to the p_i-th pair. As a response, print n integers a_1, a_2, ..., a_n in a single line. These should contain exactly one number from each pair.
Regardless of who you chose to play as the interactor will finish by printing a single integer: 0 if your answer for the test case is correct (that is, you are playing as First and it cannot choose adequate numbers from your pairs, or you are playing as Second and your chosen numbers add up to a multiple of 2n), or -1 if it is incorrect. In particular, the interactor will not print the chosen numbers if you choose to play First and lose. In either case, your program should terminate immediately after reading this number.
If at any point you make an invalid interaction, the interactor will print -1 and finish the interaction. You will receive a Wrong Answer verdict. Make sure to terminate immediately to avoid getting other verdicts.
After printing something do not forget to output end of line and flush the output. Otherwise, you will get Idleness limit exceeded. To do this, use:
* fflush(stdout) or cout.flush() in C++;
* System.out.flush() in Java;
* flush(output) in Pascal;
* stdout.flush() in Python;
* see documentation for other languages.
Hack Format
To hack, use the following format:
The first line contains an integer n (1 β€ n β€ 5 β
10^5).
The second line contains 2n integers p_1, p_2, ..., p_{2n}, denoting that the number i belongs to the p_i-th pair if the solution being hacked chooses to play as Second. If the solution being hacked chooses to play as First, those pairs don't matter but the p_1, p_2, ..., p_{2n} must still form a valid partition of 1, 2, ..., 2n into n disjoint pairs.
Examples
Input
2
1 1 2 2
0
Output
Second
1 3
Input
2
0
Output
First
2 1 2 1
Note
In the first sample, n = 2, and you decide to play as Second. The judge chooses the pairs (1, 2) and (3, 4), and you reply with the numbers 1 and 3. This is a valid choice since it contains exactly one number from each pair, and the sum 1 + 3 = 4 is divisible by 4.
In the second sample, n = 2 again, and you play as First. You choose the pairs (2, 4) and (1, 3). The judge fails to choose a number from each pair such that their sum is divisible by 4, so the answer is correct.
Note that the sample tests are just for illustration of the interaction protocol, and don't necessarily correspond to the behavior of the real interactor.
Submitted Solution:
```
import sys
import random
n = int(input())
sys.stdout.flush()
if n%4 == 2:
print("First")
sys.stdout.flush()
odp = []
for i in range(2*n):
if i % 4 == 0:
odp.append(i//2 + 1)
if i % 4 == 1:
odp.append(i//2 + 2)
if i % 4 == 2:
odp.append(i//2)
if i % 4 == 3:
odp.append(i//2 + 1)
print(*odp)
u = int(input())
sys.stdout.flush()
sys.exit(0)
elif n%4 == 0:
print("First")
sys.stdout.flush()
odp = list(range(1,n+1)) + list(range(1,n+1))
print(*odp)
u = int(input())
sys.stdout.flush()
sys.exit(0)
else:
print("Second")
sys.stdout.flush()
pary = [[] for i in range(n)]
l = list(map(int,input().split()))
for i in range(2*n):
pary[l[i]-1].append(i + 1)
moje = [0 for i in range(n)]
a = 0
for i in range(n):
a += pary[i][0]
while a%n != 0:
x = random.randint(0,n)
moje[x] = (moje[x]+1)%2
a += pary[x][moje[x]]
a -= pary[x][(moje[x]-1)%2]
odp = [pary[i][moje[i]] for i in range(n)]
print(*odp)
sys.stdout.flush()
u = int(input())
sys.stdout.flush()
sys.exit(0)
```
No
| 90,331 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Vasya goes to visit his classmate Petya. Vasya knows that Petya's apartment number is n.
There is only one entrance in Petya's house and the distribution of apartments is the following: the first floor contains 2 apartments, every other floor contains x apartments each. Apartments are numbered starting from one, from the first floor. I.e. apartments on the first floor have numbers 1 and 2, apartments on the second floor have numbers from 3 to (x + 2), apartments on the third floor have numbers from (x + 3) to (2 β
x + 2), and so on.
Your task is to find the number of floor on which Petya lives. Assume that the house is always high enough to fit at least n apartments.
You have to answer t independent test cases.
Input
The first line of the input contains one integer t (1 β€ t β€ 1000) β the number of test cases. Then t test cases follow.
The only line of the test case contains two integers n and x (1 β€ n, x β€ 1000) β the number of Petya's apartment and the number of apartments on each floor of the house except the first one (there are two apartments on the first floor).
Output
For each test case, print the answer: the number of floor on which Petya lives.
Example
Input
4
7 3
1 5
22 5
987 13
Output
3
1
5
77
Note
Consider the first test case of the example: the first floor contains apartments with numbers 1 and 2, the second one contains apartments with numbers 3, 4 and 5, the third one contains apartments with numbers 6, 7 and 8. Therefore, Petya lives on the third floor.
In the second test case of the example, Petya lives in the apartment 1 which is on the first floor.
Tags: implementation, math
Correct Solution:
```
t = int(input())
for i in range(t):
n, x = [int(i) for i in input().split()]
a = 0
if n <= 2:
print(1)
else:
n -= 2
while n > 0:
n -= x
a += 1
a += 1
print(a)
```
| 90,332 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Vasya goes to visit his classmate Petya. Vasya knows that Petya's apartment number is n.
There is only one entrance in Petya's house and the distribution of apartments is the following: the first floor contains 2 apartments, every other floor contains x apartments each. Apartments are numbered starting from one, from the first floor. I.e. apartments on the first floor have numbers 1 and 2, apartments on the second floor have numbers from 3 to (x + 2), apartments on the third floor have numbers from (x + 3) to (2 β
x + 2), and so on.
Your task is to find the number of floor on which Petya lives. Assume that the house is always high enough to fit at least n apartments.
You have to answer t independent test cases.
Input
The first line of the input contains one integer t (1 β€ t β€ 1000) β the number of test cases. Then t test cases follow.
The only line of the test case contains two integers n and x (1 β€ n, x β€ 1000) β the number of Petya's apartment and the number of apartments on each floor of the house except the first one (there are two apartments on the first floor).
Output
For each test case, print the answer: the number of floor on which Petya lives.
Example
Input
4
7 3
1 5
22 5
987 13
Output
3
1
5
77
Note
Consider the first test case of the example: the first floor contains apartments with numbers 1 and 2, the second one contains apartments with numbers 3, 4 and 5, the third one contains apartments with numbers 6, 7 and 8. Therefore, Petya lives on the third floor.
In the second test case of the example, Petya lives in the apartment 1 which is on the first floor.
Tags: implementation, math
Correct Solution:
```
import math
n1 = int(input())
for _ in range(n1):
n2 = input()
l = [int(item) for item in n2.split()]
n,x = l[0],l[1]
if n<=2 : print(1)
else : print(1+math.ceil((n-2)/x))
```
| 90,333 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Vasya goes to visit his classmate Petya. Vasya knows that Petya's apartment number is n.
There is only one entrance in Petya's house and the distribution of apartments is the following: the first floor contains 2 apartments, every other floor contains x apartments each. Apartments are numbered starting from one, from the first floor. I.e. apartments on the first floor have numbers 1 and 2, apartments on the second floor have numbers from 3 to (x + 2), apartments on the third floor have numbers from (x + 3) to (2 β
x + 2), and so on.
Your task is to find the number of floor on which Petya lives. Assume that the house is always high enough to fit at least n apartments.
You have to answer t independent test cases.
Input
The first line of the input contains one integer t (1 β€ t β€ 1000) β the number of test cases. Then t test cases follow.
The only line of the test case contains two integers n and x (1 β€ n, x β€ 1000) β the number of Petya's apartment and the number of apartments on each floor of the house except the first one (there are two apartments on the first floor).
Output
For each test case, print the answer: the number of floor on which Petya lives.
Example
Input
4
7 3
1 5
22 5
987 13
Output
3
1
5
77
Note
Consider the first test case of the example: the first floor contains apartments with numbers 1 and 2, the second one contains apartments with numbers 3, 4 and 5, the third one contains apartments with numbers 6, 7 and 8. Therefore, Petya lives on the third floor.
In the second test case of the example, Petya lives in the apartment 1 which is on the first floor.
Tags: implementation, math
Correct Solution:
```
t=int(input())
for i in range(t):
n,x=map(int,input().split())
print(max(0,(n-3)//x+1)+1)
```
| 90,334 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Vasya goes to visit his classmate Petya. Vasya knows that Petya's apartment number is n.
There is only one entrance in Petya's house and the distribution of apartments is the following: the first floor contains 2 apartments, every other floor contains x apartments each. Apartments are numbered starting from one, from the first floor. I.e. apartments on the first floor have numbers 1 and 2, apartments on the second floor have numbers from 3 to (x + 2), apartments on the third floor have numbers from (x + 3) to (2 β
x + 2), and so on.
Your task is to find the number of floor on which Petya lives. Assume that the house is always high enough to fit at least n apartments.
You have to answer t independent test cases.
Input
The first line of the input contains one integer t (1 β€ t β€ 1000) β the number of test cases. Then t test cases follow.
The only line of the test case contains two integers n and x (1 β€ n, x β€ 1000) β the number of Petya's apartment and the number of apartments on each floor of the house except the first one (there are two apartments on the first floor).
Output
For each test case, print the answer: the number of floor on which Petya lives.
Example
Input
4
7 3
1 5
22 5
987 13
Output
3
1
5
77
Note
Consider the first test case of the example: the first floor contains apartments with numbers 1 and 2, the second one contains apartments with numbers 3, 4 and 5, the third one contains apartments with numbers 6, 7 and 8. Therefore, Petya lives on the third floor.
In the second test case of the example, Petya lives in the apartment 1 which is on the first floor.
Tags: implementation, math
Correct Solution:
```
#codeforces div-2 round 668
'''for i in range(int(input())):
n=int(input())
arr=[int(i) for i in input().split()]
print(*arr[::-1])'''
'''for i in range(int(input())):
n=int(input())
arr=[int(i) for i in input().split()]
run=0
for i in range(n-1,-1,-1):
if arr[i]<0:
run+=arr[i]
else:
if run<0:
temp=arr[i]
arr[i]=max(0,arr[i]+run)
run=min(0,temp+run)
res=0
for i in range(n):
res+=arr[i] if arr[i]>0 else 0
print(res)'''
"""for i in range(int(input())):
n,k=[int(i) for i in input().split()]
s=intput()"""
#Codechef long challenge
'''from collections import defaultdict
for i in range(int(input())):
n=int(input())
arr=[int(i) for i in input().split()]
cnt=defaultdict(int)
for i in range(n):
cnt[arr[i]]+=1
print(len(cnt))'''
#Codeforces round 669 div-02
'''for i in range(int(input())):
n=int(input())
arr=[int(i) for i in input().split()]
ones=0
for i in range(n):
if arr[i]==1:
ones+=1
if ones<=n//2:
print(n-ones)
print(*[0 for j in range(n-ones)])
elif ones%2:
print(ones-1)
print(*[1 for j in range(ones-1)])
else:
print(ones)
print(*[1 for j in range(ones)])'''
'''def gcd(a,b):
if b==0:
return a
return gcd(b,a%b)
for i in range(int(input())):
n=int(input())
arr=[int(i) for i in input().split()]
k=max(arr)
imp=[]
run=k
arr0=arr[:]
for j in range(n):
for i in range(len(arr0)):
for i in range(n):
imp.append((gcd(k,arr[i]),arr[i]))
print(imp)
imp.sort(key=lambda x:x[0],reverse=True)
res=[]
for i in imp:
res.append(i[1])
print(*res)'''
#Codeforces round 670 DIV-02
'''from collections import defaultdict
for i in range(int(input())):
n=int(input())
arr=[int(i) for i in input().split()]
cnt=defaultdict(int)
for i in arr:
cnt[i]+=1
first=0
second=0
tot=0
for j in range(0,max(arr)+2):
if cnt[j]==0:
first=j
break
res=0
for t in range(0,max(arr)+2):
if cnt[t]==1 or cnt[t]==0:
second=t
break
print(first+second)'''
'''for i in range(int(input())):
n=int(input())
arr=[int(i) for i in input().split()]
arr.sort()
pre=[arr[0] for i in range(len(arr))]
suff=[arr[-1] for i in range(len(arr))]
for i in range(1,n):
pre[i]=pre[i-1]*arr[i]
for j in range(n-2,-1,-1):
suff[j]=suff[j+1]*arr[j]
res=float("-inf")
if n>=5:
res=max(res,pre[1]*suff[-3],pre[3]*suff[-1],suff[-5])
print(res)
pos=[]
zero=0
neg=[]
res=0
for i in range(n):
if arr[i]>0:
pos.append(arr[i])
elif arr[i]==0:
zero+=1
else:
neg.append(arr[i])
pos.sort(reverse=True)
neg.sort()
pos_pro=[pos[0] for i in range(len(pos))]
neg_pro=[neg[0] for i in range(len(neg))]
if len(pos)>1:
for k in range(1,len(pos)):
pos_pro[k]=pos_pro[k-1]*pos[k]
if len(neg)>1:
for k in range(1,len(neg)):
neg_pro[k]=neg_pro[k-1]*neg[k]
if len(pos)>=5:
if len(neg)>=4:
res=max(res,pos_pro[4],pos_pro[2]*neg_pro[1],pos_pro[0]*neg_pro[3])
elif len(neg)>=2 and len(neg)<4:
res=max(res,pos_pro[4],pos_pro[2]*neg_pro[1])
else:
res=pos_pro[4]
print(res)
else:
if len(neg)>=2 and len(neg)<4:
if len(pos)<3:
res=0
else:
res=max(res,neg_pro[1]*pos_pro[2])
elif len(neg)>=4:
if len(pos)>=1:
res=max(res,neg_pro[3]*pos_pro[0])
else:
res=0 if zero else neg_pro[-1]
print(res)'''
#Codeforces educational round
'''for i in range(int(input())):
x,y,k=[int(i) for i in input().split()]
sticks=k*(y+1)-1
if sticks%(x-1):
temp=sticks//(x-1)+1
else:
temp=sticks//(x-1)
print(temp +k )'''
'''for i in range(int(input())):
n=int(input())
arr=[int(i) for i in input().split()]
lock=[int(i) for i in input().split()]
neg=[]
for i in range(n):
if lock[i]==0:
neg.append(arr[i])
neg.sort(reverse=True)
j=0
for i in range(len(arr)):
if lock[i]==0:
arr[i]=neg[j]
j+=1
print(*arr)'''
'''for _ in range(int(input())):
n=int(input())
arr=[int(i) for i in input().split()]
if n==1:
print(arr[0])
else:
dp=[[0,0] for i in range(n)]
dp[-1]=[arr[-1],0]
dp[-2]=[arr[-2],0]
for k in range(n-3,-1,-1):
dp[k][0]=arr[k]+dp[k+1][1]
if arr[k]+arr[k+1]+dp[k+2][1]<dp[k][0]:
dp[k][0]=arr[k]+arr[k+1]+dp[k+2][1]
dp[k][1]=min(dp[k+1][0],dp[k+2][0])
print(dp[0][0])
'''
#Codeforces round 673
'''for i in range(int(input())):
n,k=[int(i) for i in input().split()]
arr=[int(i) for i in input().split()]
res=0
flag=0
temp=min(arr)
app=0
for i in range(n):
if arr[i]==temp and not app:
app=1
continue
elif arr[i]==temp and app:
res+=(k-arr[i])//temp
else:
res+=(k-arr[i])//temp
print(res)'''
'''from collections import defaultdict
for i in range(int(input())):
n,t=[int(i) for i in input().split()]
app=defaultdict(lambda:-1)
arr=[int(i) for i in input().split()]
ans=[0 for i in range(n)]
for i in range(n):
if arr[i]>t:
continue
elif app[t-arr[i]]!=-1:
ans[i]=ans[app[t-arr[i]]]^1
app[arr[i]]=i
else:
app[arr[i]]=i
print(*ans)'''
'''for i in range(int(input())):
n=int(input())
arr=[int(i) for i in input().split()]
where={}
for i in range(n):
if arr[i] in where:
where[arr[i]].append(i)
else:
where[arr[i]]=[i]
ans=[-1 for i in range(n)]
last=0
for k in range(1,n+1):
if k not in where:
continue
else:
res=0
for t in range(1,len(where[k])):
res=max(res,where[k][t]-where[k][t-1])
res=max(res,where[k][0]+1,n-where[k][-1])
if res>0 and ans[res-1]==-1:
ans[res-1]=k
mn=-1
for i in range(n):
if ans[i]!=-1 and mn<ans[i]:
ans[i]=mn
elif ans[i]==-1:
ans[i]=mn
else:
mn=min(mn if mn!=-1 else float("inf"),ans[i])
print(ans[i],end=" ")'''
#Codeforces round 674 DIV-3
for i in range(int(input())):
n,x=[int(i) for i in input().split()]
if n<3:
print(1)
else:
temp=(n-2)//x
temp+=1 if (n-2)%x!=0 else 0
print(1+temp)
```
| 90,335 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Vasya goes to visit his classmate Petya. Vasya knows that Petya's apartment number is n.
There is only one entrance in Petya's house and the distribution of apartments is the following: the first floor contains 2 apartments, every other floor contains x apartments each. Apartments are numbered starting from one, from the first floor. I.e. apartments on the first floor have numbers 1 and 2, apartments on the second floor have numbers from 3 to (x + 2), apartments on the third floor have numbers from (x + 3) to (2 β
x + 2), and so on.
Your task is to find the number of floor on which Petya lives. Assume that the house is always high enough to fit at least n apartments.
You have to answer t independent test cases.
Input
The first line of the input contains one integer t (1 β€ t β€ 1000) β the number of test cases. Then t test cases follow.
The only line of the test case contains two integers n and x (1 β€ n, x β€ 1000) β the number of Petya's apartment and the number of apartments on each floor of the house except the first one (there are two apartments on the first floor).
Output
For each test case, print the answer: the number of floor on which Petya lives.
Example
Input
4
7 3
1 5
22 5
987 13
Output
3
1
5
77
Note
Consider the first test case of the example: the first floor contains apartments with numbers 1 and 2, the second one contains apartments with numbers 3, 4 and 5, the third one contains apartments with numbers 6, 7 and 8. Therefore, Petya lives on the third floor.
In the second test case of the example, Petya lives in the apartment 1 which is on the first floor.
Tags: implementation, math
Correct Solution:
```
for _ in range(int(input())):
sim=2
n,x=map(int, input().split())
if n<=sim:
print(1)
else:
while n>sim:
sim+=x
print(int((sim-2)/x+1))
```
| 90,336 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Vasya goes to visit his classmate Petya. Vasya knows that Petya's apartment number is n.
There is only one entrance in Petya's house and the distribution of apartments is the following: the first floor contains 2 apartments, every other floor contains x apartments each. Apartments are numbered starting from one, from the first floor. I.e. apartments on the first floor have numbers 1 and 2, apartments on the second floor have numbers from 3 to (x + 2), apartments on the third floor have numbers from (x + 3) to (2 β
x + 2), and so on.
Your task is to find the number of floor on which Petya lives. Assume that the house is always high enough to fit at least n apartments.
You have to answer t independent test cases.
Input
The first line of the input contains one integer t (1 β€ t β€ 1000) β the number of test cases. Then t test cases follow.
The only line of the test case contains two integers n and x (1 β€ n, x β€ 1000) β the number of Petya's apartment and the number of apartments on each floor of the house except the first one (there are two apartments on the first floor).
Output
For each test case, print the answer: the number of floor on which Petya lives.
Example
Input
4
7 3
1 5
22 5
987 13
Output
3
1
5
77
Note
Consider the first test case of the example: the first floor contains apartments with numbers 1 and 2, the second one contains apartments with numbers 3, 4 and 5, the third one contains apartments with numbers 6, 7 and 8. Therefore, Petya lives on the third floor.
In the second test case of the example, Petya lives in the apartment 1 which is on the first floor.
Tags: implementation, math
Correct Solution:
```
for _ in range(int(input())):
n,x=map(int,input().split())
if n<=2:
print(1)
else:
n-=2
s=n/x
if int(s)!=s:
s=int(s)+1
print(int(s)+1)
```
| 90,337 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Vasya goes to visit his classmate Petya. Vasya knows that Petya's apartment number is n.
There is only one entrance in Petya's house and the distribution of apartments is the following: the first floor contains 2 apartments, every other floor contains x apartments each. Apartments are numbered starting from one, from the first floor. I.e. apartments on the first floor have numbers 1 and 2, apartments on the second floor have numbers from 3 to (x + 2), apartments on the third floor have numbers from (x + 3) to (2 β
x + 2), and so on.
Your task is to find the number of floor on which Petya lives. Assume that the house is always high enough to fit at least n apartments.
You have to answer t independent test cases.
Input
The first line of the input contains one integer t (1 β€ t β€ 1000) β the number of test cases. Then t test cases follow.
The only line of the test case contains two integers n and x (1 β€ n, x β€ 1000) β the number of Petya's apartment and the number of apartments on each floor of the house except the first one (there are two apartments on the first floor).
Output
For each test case, print the answer: the number of floor on which Petya lives.
Example
Input
4
7 3
1 5
22 5
987 13
Output
3
1
5
77
Note
Consider the first test case of the example: the first floor contains apartments with numbers 1 and 2, the second one contains apartments with numbers 3, 4 and 5, the third one contains apartments with numbers 6, 7 and 8. Therefore, Petya lives on the third floor.
In the second test case of the example, Petya lives in the apartment 1 which is on the first floor.
Tags: implementation, math
Correct Solution:
```
import math
n1=int(input())
for x in range(n1):
n2=input().split(" ")
a=int(n2[0])
b=int(n2[1])
if(a<=2):
print(1)
else:
print(1+math.ceil((a-2)/b))
```
| 90,338 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Vasya goes to visit his classmate Petya. Vasya knows that Petya's apartment number is n.
There is only one entrance in Petya's house and the distribution of apartments is the following: the first floor contains 2 apartments, every other floor contains x apartments each. Apartments are numbered starting from one, from the first floor. I.e. apartments on the first floor have numbers 1 and 2, apartments on the second floor have numbers from 3 to (x + 2), apartments on the third floor have numbers from (x + 3) to (2 β
x + 2), and so on.
Your task is to find the number of floor on which Petya lives. Assume that the house is always high enough to fit at least n apartments.
You have to answer t independent test cases.
Input
The first line of the input contains one integer t (1 β€ t β€ 1000) β the number of test cases. Then t test cases follow.
The only line of the test case contains two integers n and x (1 β€ n, x β€ 1000) β the number of Petya's apartment and the number of apartments on each floor of the house except the first one (there are two apartments on the first floor).
Output
For each test case, print the answer: the number of floor on which Petya lives.
Example
Input
4
7 3
1 5
22 5
987 13
Output
3
1
5
77
Note
Consider the first test case of the example: the first floor contains apartments with numbers 1 and 2, the second one contains apartments with numbers 3, 4 and 5, the third one contains apartments with numbers 6, 7 and 8. Therefore, Petya lives on the third floor.
In the second test case of the example, Petya lives in the apartment 1 which is on the first floor.
Tags: implementation, math
Correct Solution:
```
def read_int():
return int(input())
def read_ints():
return map(int, input().split(' '))
t = read_int()
for case_num in range(t):
fn = 1
cnt = 2
n, x = read_ints()
if n <= 2:
print(1)
else:
while cnt < n:
cnt += x
fn += 1
print(fn)
fn = 1
```
| 90,339 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Vasya goes to visit his classmate Petya. Vasya knows that Petya's apartment number is n.
There is only one entrance in Petya's house and the distribution of apartments is the following: the first floor contains 2 apartments, every other floor contains x apartments each. Apartments are numbered starting from one, from the first floor. I.e. apartments on the first floor have numbers 1 and 2, apartments on the second floor have numbers from 3 to (x + 2), apartments on the third floor have numbers from (x + 3) to (2 β
x + 2), and so on.
Your task is to find the number of floor on which Petya lives. Assume that the house is always high enough to fit at least n apartments.
You have to answer t independent test cases.
Input
The first line of the input contains one integer t (1 β€ t β€ 1000) β the number of test cases. Then t test cases follow.
The only line of the test case contains two integers n and x (1 β€ n, x β€ 1000) β the number of Petya's apartment and the number of apartments on each floor of the house except the first one (there are two apartments on the first floor).
Output
For each test case, print the answer: the number of floor on which Petya lives.
Example
Input
4
7 3
1 5
22 5
987 13
Output
3
1
5
77
Note
Consider the first test case of the example: the first floor contains apartments with numbers 1 and 2, the second one contains apartments with numbers 3, 4 and 5, the third one contains apartments with numbers 6, 7 and 8. Therefore, Petya lives on the third floor.
In the second test case of the example, Petya lives in the apartment 1 which is on the first floor.
Submitted Solution:
```
for _ in range(0, int(input())):
n, x = map(int, input().split())
if n <= 2:
print(1)
else:
print(((n-3)//x)+2)
```
Yes
| 90,340 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Vasya goes to visit his classmate Petya. Vasya knows that Petya's apartment number is n.
There is only one entrance in Petya's house and the distribution of apartments is the following: the first floor contains 2 apartments, every other floor contains x apartments each. Apartments are numbered starting from one, from the first floor. I.e. apartments on the first floor have numbers 1 and 2, apartments on the second floor have numbers from 3 to (x + 2), apartments on the third floor have numbers from (x + 3) to (2 β
x + 2), and so on.
Your task is to find the number of floor on which Petya lives. Assume that the house is always high enough to fit at least n apartments.
You have to answer t independent test cases.
Input
The first line of the input contains one integer t (1 β€ t β€ 1000) β the number of test cases. Then t test cases follow.
The only line of the test case contains two integers n and x (1 β€ n, x β€ 1000) β the number of Petya's apartment and the number of apartments on each floor of the house except the first one (there are two apartments on the first floor).
Output
For each test case, print the answer: the number of floor on which Petya lives.
Example
Input
4
7 3
1 5
22 5
987 13
Output
3
1
5
77
Note
Consider the first test case of the example: the first floor contains apartments with numbers 1 and 2, the second one contains apartments with numbers 3, 4 and 5, the third one contains apartments with numbers 6, 7 and 8. Therefore, Petya lives on the third floor.
In the second test case of the example, Petya lives in the apartment 1 which is on the first floor.
Submitted Solution:
```
# import itertools as it
# import functools as ft
import math
teststring = """4
7 3
1 5
22 5
987 13
"""
online = __file__ != "/home/jhli/py/674/Problem_A.py"
true, false = True, False
if True:
def spitout():
for c in teststring.splitlines():
yield c
_ito = spitout()
if not online:
def input():
return next(_ito)
def build_enum(*a):
built = dict()
for i, c in enumerate(a):
built[c] = i
return lambda x: built[x]
# T = 1
T = int(input())
##-----------------start coding-----------------
for ti in range(1, T + 1):
[n, x] = map(int, input().split(" "))
if n <= 2:
print(1)
else:
print(int(math.ceil((n-2)/x))+1)
# print('Case #{}: {}'.format(ti, '...'))
```
Yes
| 90,341 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Vasya goes to visit his classmate Petya. Vasya knows that Petya's apartment number is n.
There is only one entrance in Petya's house and the distribution of apartments is the following: the first floor contains 2 apartments, every other floor contains x apartments each. Apartments are numbered starting from one, from the first floor. I.e. apartments on the first floor have numbers 1 and 2, apartments on the second floor have numbers from 3 to (x + 2), apartments on the third floor have numbers from (x + 3) to (2 β
x + 2), and so on.
Your task is to find the number of floor on which Petya lives. Assume that the house is always high enough to fit at least n apartments.
You have to answer t independent test cases.
Input
The first line of the input contains one integer t (1 β€ t β€ 1000) β the number of test cases. Then t test cases follow.
The only line of the test case contains two integers n and x (1 β€ n, x β€ 1000) β the number of Petya's apartment and the number of apartments on each floor of the house except the first one (there are two apartments on the first floor).
Output
For each test case, print the answer: the number of floor on which Petya lives.
Example
Input
4
7 3
1 5
22 5
987 13
Output
3
1
5
77
Note
Consider the first test case of the example: the first floor contains apartments with numbers 1 and 2, the second one contains apartments with numbers 3, 4 and 5, the third one contains apartments with numbers 6, 7 and 8. Therefore, Petya lives on the third floor.
In the second test case of the example, Petya lives in the apartment 1 which is on the first floor.
Submitted Solution:
```
for __ in range(int(input())):
n, x = list(map(int, input().split()))
ans = 1
n -= 2
num = x
while n > 0:
if num == x:
ans += 1
num = 0
n -= 1
num += 1
print(ans)
```
Yes
| 90,342 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Vasya goes to visit his classmate Petya. Vasya knows that Petya's apartment number is n.
There is only one entrance in Petya's house and the distribution of apartments is the following: the first floor contains 2 apartments, every other floor contains x apartments each. Apartments are numbered starting from one, from the first floor. I.e. apartments on the first floor have numbers 1 and 2, apartments on the second floor have numbers from 3 to (x + 2), apartments on the third floor have numbers from (x + 3) to (2 β
x + 2), and so on.
Your task is to find the number of floor on which Petya lives. Assume that the house is always high enough to fit at least n apartments.
You have to answer t independent test cases.
Input
The first line of the input contains one integer t (1 β€ t β€ 1000) β the number of test cases. Then t test cases follow.
The only line of the test case contains two integers n and x (1 β€ n, x β€ 1000) β the number of Petya's apartment and the number of apartments on each floor of the house except the first one (there are two apartments on the first floor).
Output
For each test case, print the answer: the number of floor on which Petya lives.
Example
Input
4
7 3
1 5
22 5
987 13
Output
3
1
5
77
Note
Consider the first test case of the example: the first floor contains apartments with numbers 1 and 2, the second one contains apartments with numbers 3, 4 and 5, the third one contains apartments with numbers 6, 7 and 8. Therefore, Petya lives on the third floor.
In the second test case of the example, Petya lives in the apartment 1 which is on the first floor.
Submitted Solution:
```
t = int(input())
from math import ceil
for _ in range(t):
n,x = map(int, input().split(' '))
if n == 1 or n == 2:
print(1)
else:
print(ceil((n-2)/x)+1)
```
Yes
| 90,343 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Vasya goes to visit his classmate Petya. Vasya knows that Petya's apartment number is n.
There is only one entrance in Petya's house and the distribution of apartments is the following: the first floor contains 2 apartments, every other floor contains x apartments each. Apartments are numbered starting from one, from the first floor. I.e. apartments on the first floor have numbers 1 and 2, apartments on the second floor have numbers from 3 to (x + 2), apartments on the third floor have numbers from (x + 3) to (2 β
x + 2), and so on.
Your task is to find the number of floor on which Petya lives. Assume that the house is always high enough to fit at least n apartments.
You have to answer t independent test cases.
Input
The first line of the input contains one integer t (1 β€ t β€ 1000) β the number of test cases. Then t test cases follow.
The only line of the test case contains two integers n and x (1 β€ n, x β€ 1000) β the number of Petya's apartment and the number of apartments on each floor of the house except the first one (there are two apartments on the first floor).
Output
For each test case, print the answer: the number of floor on which Petya lives.
Example
Input
4
7 3
1 5
22 5
987 13
Output
3
1
5
77
Note
Consider the first test case of the example: the first floor contains apartments with numbers 1 and 2, the second one contains apartments with numbers 3, 4 and 5, the third one contains apartments with numbers 6, 7 and 8. Therefore, Petya lives on the third floor.
In the second test case of the example, Petya lives in the apartment 1 which is on the first floor.
Submitted Solution:
```
import math
t = int(input())
for i in range(t):
n,x = map(int,input().split())
if(x==1 or x==2):
print(1)
elif(n%x>2):
a = math.ceil(n/x) + 1
print(a)
else:
a = math.ceil((n/x))
print(a)
```
No
| 90,344 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Vasya goes to visit his classmate Petya. Vasya knows that Petya's apartment number is n.
There is only one entrance in Petya's house and the distribution of apartments is the following: the first floor contains 2 apartments, every other floor contains x apartments each. Apartments are numbered starting from one, from the first floor. I.e. apartments on the first floor have numbers 1 and 2, apartments on the second floor have numbers from 3 to (x + 2), apartments on the third floor have numbers from (x + 3) to (2 β
x + 2), and so on.
Your task is to find the number of floor on which Petya lives. Assume that the house is always high enough to fit at least n apartments.
You have to answer t independent test cases.
Input
The first line of the input contains one integer t (1 β€ t β€ 1000) β the number of test cases. Then t test cases follow.
The only line of the test case contains two integers n and x (1 β€ n, x β€ 1000) β the number of Petya's apartment and the number of apartments on each floor of the house except the first one (there are two apartments on the first floor).
Output
For each test case, print the answer: the number of floor on which Petya lives.
Example
Input
4
7 3
1 5
22 5
987 13
Output
3
1
5
77
Note
Consider the first test case of the example: the first floor contains apartments with numbers 1 and 2, the second one contains apartments with numbers 3, 4 and 5, the third one contains apartments with numbers 6, 7 and 8. Therefore, Petya lives on the third floor.
In the second test case of the example, Petya lives in the apartment 1 which is on the first floor.
Submitted Solution:
```
t = int(input())
while t:
a = input()
n,x=[int(x) for x in a.split()]
if n==1 or n==2:
print(1)
t-=1
continue
k = (int(n-2)/x)+2
t-=1
```
No
| 90,345 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Vasya goes to visit his classmate Petya. Vasya knows that Petya's apartment number is n.
There is only one entrance in Petya's house and the distribution of apartments is the following: the first floor contains 2 apartments, every other floor contains x apartments each. Apartments are numbered starting from one, from the first floor. I.e. apartments on the first floor have numbers 1 and 2, apartments on the second floor have numbers from 3 to (x + 2), apartments on the third floor have numbers from (x + 3) to (2 β
x + 2), and so on.
Your task is to find the number of floor on which Petya lives. Assume that the house is always high enough to fit at least n apartments.
You have to answer t independent test cases.
Input
The first line of the input contains one integer t (1 β€ t β€ 1000) β the number of test cases. Then t test cases follow.
The only line of the test case contains two integers n and x (1 β€ n, x β€ 1000) β the number of Petya's apartment and the number of apartments on each floor of the house except the first one (there are two apartments on the first floor).
Output
For each test case, print the answer: the number of floor on which Petya lives.
Example
Input
4
7 3
1 5
22 5
987 13
Output
3
1
5
77
Note
Consider the first test case of the example: the first floor contains apartments with numbers 1 and 2, the second one contains apartments with numbers 3, 4 and 5, the third one contains apartments with numbers 6, 7 and 8. Therefore, Petya lives on the third floor.
In the second test case of the example, Petya lives in the apartment 1 which is on the first floor.
Submitted Solution:
```
t=int(input())
for i in range(t):
n,x=map(int,input().split())
if n<=2:
print("1")
else:
n-=2
flor=round(n/x)
print(flor+1)
```
No
| 90,346 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Vasya goes to visit his classmate Petya. Vasya knows that Petya's apartment number is n.
There is only one entrance in Petya's house and the distribution of apartments is the following: the first floor contains 2 apartments, every other floor contains x apartments each. Apartments are numbered starting from one, from the first floor. I.e. apartments on the first floor have numbers 1 and 2, apartments on the second floor have numbers from 3 to (x + 2), apartments on the third floor have numbers from (x + 3) to (2 β
x + 2), and so on.
Your task is to find the number of floor on which Petya lives. Assume that the house is always high enough to fit at least n apartments.
You have to answer t independent test cases.
Input
The first line of the input contains one integer t (1 β€ t β€ 1000) β the number of test cases. Then t test cases follow.
The only line of the test case contains two integers n and x (1 β€ n, x β€ 1000) β the number of Petya's apartment and the number of apartments on each floor of the house except the first one (there are two apartments on the first floor).
Output
For each test case, print the answer: the number of floor on which Petya lives.
Example
Input
4
7 3
1 5
22 5
987 13
Output
3
1
5
77
Note
Consider the first test case of the example: the first floor contains apartments with numbers 1 and 2, the second one contains apartments with numbers 3, 4 and 5, the third one contains apartments with numbers 6, 7 and 8. Therefore, Petya lives on the third floor.
In the second test case of the example, Petya lives in the apartment 1 which is on the first floor.
Submitted Solution:
```
t = int(input())
while t > 0:
n, x = map(int, input().split())
print(int((n/x) + 0.5) + 1)
t -= 1
```
No
| 90,347 |
Provide tags and a correct Python 3 solution for this coding contest problem.
There are n cities in Berland. The city numbered 1 is the capital. Some pairs of cities are connected by a one-way road of length 1.
Before the trip, Polycarp for each city found out the value of d_i β the shortest distance from the capital (the 1-st city) to the i-th city.
Polycarp begins his journey in the city with number s and, being in the i-th city, chooses one of the following actions:
1. Travel from the i-th city to the j-th city if there is a road from the i-th city to the j-th and d_i < d_j;
2. Travel from the i-th city to the j-th city if there is a road from the i-th city to the j-th and d_i β₯ d_j;
3. Stop traveling.
Since the government of Berland does not want all people to come to the capital, so Polycarp no more than once can take the second action from the list. in other words, he can perform the second action 0 or 1 time during his journey. Polycarp, on the other hand, wants to be as close to the capital as possible.
<image>
For example, if n = 6 and the cities are connected, as in the picture above, then Polycarp could have made the following travels (not all possible options):
* 2 β 5 β 1 β 2 β 5;
* 3 β 6 β 2;
* 1 β 3 β 6 β 2 β 5.
Polycarp wants for each starting city i to find out how close he can get to the capital. More formally: he wants to find the minimal value of d_j that Polycarp can get from the city i to the city j according to the rules described above.
Input
The first line contains one integer t (1 β€ t β€ 10^4) β the number of test cases. Then t test cases follow.
Each test case is preceded by an empty line.
The first line of each test case contains two integers n (2 β€ n β€ 2 β
10^5) and m (1 β€ m β€ 2 β
10^5) β number of cities and roads, respectively.
This is followed by m lines describing the roads. Each road is characterized by two integers u and v (1 β€ u, v β€ n, u β v) β the numbers of cities connected by a one-way road.
It is guaranteed that the sums of n and m over all test cases do not exceed 2 β
10^5.
It is guaranteed that for each pair of different cities (u, v) there is at most one road from u to v (but a pair of roads from u to v and from v to u β is valid).
It is guaranteed that there is a path from the capital to all cities.
Output
For each test case, on a separate line output n numbers, the i-th of which is equal to the minimum possible distance from the capital to the city where Polycarp ended his journey.
Example
Input
3
6 7
1 2
1 3
2 5
2 4
5 1
3 6
6 2
2 2
1 2
2 1
6 8
1 2
1 5
2 6
6 1
2 3
3 4
4 2
5 4
Output
0 0 1 2 0 1
0 0
0 0 2 1 1 0
Tags: dfs and similar, dp, graphs, shortest paths
Correct Solution:
```
"""
#If FastIO not needed, use this and don't forget to strip
#import sys, math
#input = sys.stdin.readline
"""
import os
import sys
from io import BytesIO, IOBase
import heapq as h
from bisect import bisect_left, bisect_right
import time
from types import GeneratorType
BUFSIZE = 8192
class FastIO(IOBase):
newlines = 0
def __init__(self, file):
import os
self.os = os
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 = self.os.read(self._fd, max(self.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 = self.os.read(self._fd, max(self.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:
self.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 collections import defaultdict as dd, deque as dq, Counter as dc
import math, string
start_time = time.time()
def getInts():
return [int(s) for s in input().split()]
def getInt():
return int(input())
def getStrs():
return [s for s in input().split()]
def getStr():
return input()
def listStr():
return list(input())
def getMat(n):
return [getInts() for _ in range(n)]
def isInt(s):
return '0' <= s[0] <= '9'
MOD = 10**9 + 7
"""
"""
def bootstrap(f, stack=[]):
def wrappedfunc(*args, **kwargs):
if stack:
return f(*args, **kwargs)
else:
to = f(*args, **kwargs)
while True:
if type(to) is GeneratorType:
stack.append(to)
to = next(to)
else:
stack.pop()
if not stack:
break
to = stack[-1].send(to)
return to
return wrappedfunc
def solve():
x = input()
N, M = getInts()
graph = dd(set)
for m in range(M):
U, V = getInts()
U -= 1
V -= 1
graph[U].add(V)
D = [0]*N
def bfs(node):
queue = dq([])
queue.append((node,0))
visited = set()
visited.add(node)
while queue:
node, level = queue.popleft()
for neigh in graph[node]:
if neigh not in visited:
D[neigh] = level+1
visited.add(neigh)
queue.append((neigh,level+1))
bfs(0)
visited = set()
ans = [0]*N
@bootstrap
def dfs(node):
visited.add(node)
ans[node] = D[node]
for neigh in graph[node]:
if neigh not in visited and D[node] < D[neigh]:
yield dfs(neigh)
if D[node] < D[neigh]:
ans[node] = min(ans[node],ans[neigh])
else:
ans[node] = min(ans[node],D[neigh])
yield
dfs(0)
print(*ans)
return
for _ in range(getInt()):
#print(solve())
solve()
#print(time.time()-start_time)
```
| 90,348 |
Provide tags and a correct Python 3 solution for this coding contest problem.
There are n cities in Berland. The city numbered 1 is the capital. Some pairs of cities are connected by a one-way road of length 1.
Before the trip, Polycarp for each city found out the value of d_i β the shortest distance from the capital (the 1-st city) to the i-th city.
Polycarp begins his journey in the city with number s and, being in the i-th city, chooses one of the following actions:
1. Travel from the i-th city to the j-th city if there is a road from the i-th city to the j-th and d_i < d_j;
2. Travel from the i-th city to the j-th city if there is a road from the i-th city to the j-th and d_i β₯ d_j;
3. Stop traveling.
Since the government of Berland does not want all people to come to the capital, so Polycarp no more than once can take the second action from the list. in other words, he can perform the second action 0 or 1 time during his journey. Polycarp, on the other hand, wants to be as close to the capital as possible.
<image>
For example, if n = 6 and the cities are connected, as in the picture above, then Polycarp could have made the following travels (not all possible options):
* 2 β 5 β 1 β 2 β 5;
* 3 β 6 β 2;
* 1 β 3 β 6 β 2 β 5.
Polycarp wants for each starting city i to find out how close he can get to the capital. More formally: he wants to find the minimal value of d_j that Polycarp can get from the city i to the city j according to the rules described above.
Input
The first line contains one integer t (1 β€ t β€ 10^4) β the number of test cases. Then t test cases follow.
Each test case is preceded by an empty line.
The first line of each test case contains two integers n (2 β€ n β€ 2 β
10^5) and m (1 β€ m β€ 2 β
10^5) β number of cities and roads, respectively.
This is followed by m lines describing the roads. Each road is characterized by two integers u and v (1 β€ u, v β€ n, u β v) β the numbers of cities connected by a one-way road.
It is guaranteed that the sums of n and m over all test cases do not exceed 2 β
10^5.
It is guaranteed that for each pair of different cities (u, v) there is at most one road from u to v (but a pair of roads from u to v and from v to u β is valid).
It is guaranteed that there is a path from the capital to all cities.
Output
For each test case, on a separate line output n numbers, the i-th of which is equal to the minimum possible distance from the capital to the city where Polycarp ended his journey.
Example
Input
3
6 7
1 2
1 3
2 5
2 4
5 1
3 6
6 2
2 2
1 2
2 1
6 8
1 2
1 5
2 6
6 1
2 3
3 4
4 2
5 4
Output
0 0 1 2 0 1
0 0
0 0 2 1 1 0
Tags: dfs and similar, dp, graphs, shortest paths
Correct Solution:
```
import math,sys
#from itertools import permutations, combinations;import heapq,random;
from collections import defaultdict,deque
import bisect as bi
def yes():print('YES')
def no():print('NO')
#sys.stdin=open('input.txt','r');sys.stdout=open('output.txt','w');
def I():return (int(sys.stdin.readline()))
def In():return(map(int,sys.stdin.readline().split()))
def Sn():return sys.stdin.readline().strip()
#sys.setrecursionlimit(1500)
def dict(a):
d={}
for x in a:
if d.get(x,-1)!=-1:
d[x]+=1
else:
d[x]=1
return d
def find_gt(a, x):
'Find leftmost value greater than x'
i = bi.bisect_left(a, x)
if i != len(a):
return i
else:
return -1
from types import GeneratorType
def bootstrap(f, stack=[]):
def wrappedfunc(*args, **kwargs):
if stack:
return f(*args, **kwargs)
else:
to = f(*args, **kwargs)
while True:
if type(to) is GeneratorType:
stack.append(to)
to = next(to)
else:
stack.pop()
if not stack:
break
to = stack[-1].send(to)
return to
return wrappedfunc
@bootstrap
def dfs(d,visit,node,dp,high):
visit[node]=True
dp[node]=high[node]
for x in d[node]:
if not visit[x] and (high[node]<high[x]):
yield (dfs(d,visit,x,dp,high))
if high[node]<high[x]:
dp[node]=min(dp[node],dp[x])
else:
dp[node]=min(dp[node],high[x])
yield
def main():
try:
Extra=Sn()
d=defaultdict(list)
n,m=In()
for i in range(m):
a,b=In();d[a].append(b)
high=[-1]*(n+1);q=deque([1]);high[1]=0
while q:
node=q.popleft()
for x in d[node]:
if high[x]==-1:
high[x]=high[node]+1
q.append(x)
dp=[0]*(n+1)
# print(high)
visit=[False]*(n+1)
dfs(d,visit,1,dp,high)
print(*dp[1:])
except:
pass
M = 998244353
P = 1000000007
if __name__ == '__main__':
for _ in range(I()):main()
#for _ in range(1):main()
#End#
# ******************* All The Best ******************* #
```
| 90,349 |
Provide tags and a correct Python 3 solution for this coding contest problem.
There are n cities in Berland. The city numbered 1 is the capital. Some pairs of cities are connected by a one-way road of length 1.
Before the trip, Polycarp for each city found out the value of d_i β the shortest distance from the capital (the 1-st city) to the i-th city.
Polycarp begins his journey in the city with number s and, being in the i-th city, chooses one of the following actions:
1. Travel from the i-th city to the j-th city if there is a road from the i-th city to the j-th and d_i < d_j;
2. Travel from the i-th city to the j-th city if there is a road from the i-th city to the j-th and d_i β₯ d_j;
3. Stop traveling.
Since the government of Berland does not want all people to come to the capital, so Polycarp no more than once can take the second action from the list. in other words, he can perform the second action 0 or 1 time during his journey. Polycarp, on the other hand, wants to be as close to the capital as possible.
<image>
For example, if n = 6 and the cities are connected, as in the picture above, then Polycarp could have made the following travels (not all possible options):
* 2 β 5 β 1 β 2 β 5;
* 3 β 6 β 2;
* 1 β 3 β 6 β 2 β 5.
Polycarp wants for each starting city i to find out how close he can get to the capital. More formally: he wants to find the minimal value of d_j that Polycarp can get from the city i to the city j according to the rules described above.
Input
The first line contains one integer t (1 β€ t β€ 10^4) β the number of test cases. Then t test cases follow.
Each test case is preceded by an empty line.
The first line of each test case contains two integers n (2 β€ n β€ 2 β
10^5) and m (1 β€ m β€ 2 β
10^5) β number of cities and roads, respectively.
This is followed by m lines describing the roads. Each road is characterized by two integers u and v (1 β€ u, v β€ n, u β v) β the numbers of cities connected by a one-way road.
It is guaranteed that the sums of n and m over all test cases do not exceed 2 β
10^5.
It is guaranteed that for each pair of different cities (u, v) there is at most one road from u to v (but a pair of roads from u to v and from v to u β is valid).
It is guaranteed that there is a path from the capital to all cities.
Output
For each test case, on a separate line output n numbers, the i-th of which is equal to the minimum possible distance from the capital to the city where Polycarp ended his journey.
Example
Input
3
6 7
1 2
1 3
2 5
2 4
5 1
3 6
6 2
2 2
1 2
2 1
6 8
1 2
1 5
2 6
6 1
2 3
3 4
4 2
5 4
Output
0 0 1 2 0 1
0 0
0 0 2 1 1 0
Tags: dfs and similar, dp, graphs, shortest paths
Correct Solution:
```
import sys
def input():
return sys.stdin.readline().strip()
def mint():
return int(input())
def mints():
return map(int, input().split())
for i in range(mint()):
input()
n, m = mints()
n2 = n*2
e = [[] for i in range(n)]
eb = [[] for i in range(n)]
for i in range(m):
u, v = mints()
e[u-1].append(v-1)
eb[v-1].append(u-1)
q = [0]
d = [None]*n
d[0] = 0
i = 0
while i < len(q):
x = q[i]
i += 1
for v in e[x]:
if d[v] is None:
d[v] = d[x] + 1
q.append(v)
idx = [None]*n
for i in range(n):
idx[i] = (d[i], i)
idx.sort()
q = []
i = 0
was = [[None]*n for _ in range(2)]
ans = [int(2e9)]*n
for _, id in idx:
dd = d[id]
for s in range(2):
if was[s][id] is None:
was[s][id] = (-1,-1)
q.append((id,s))
ans[id] = min(ans[id],dd)
while i < len(q):
x, s = q[i]
i += 1
for v in eb[x]:
if d[x] > d[v]:
if was[s][v] is None:
q.append((v,s))
was[s][v] = (x, s)
ans[v] = min(ans[v],dd)
elif s == 1:
if was[0][v] is None:
q.append((v,0))
was[0][v] = (x, s)
ans[v] = min(ans[v],dd)
print(' '.join(map(str,ans)))
```
| 90,350 |
Provide tags and a correct Python 3 solution for this coding contest problem.
There are n cities in Berland. The city numbered 1 is the capital. Some pairs of cities are connected by a one-way road of length 1.
Before the trip, Polycarp for each city found out the value of d_i β the shortest distance from the capital (the 1-st city) to the i-th city.
Polycarp begins his journey in the city with number s and, being in the i-th city, chooses one of the following actions:
1. Travel from the i-th city to the j-th city if there is a road from the i-th city to the j-th and d_i < d_j;
2. Travel from the i-th city to the j-th city if there is a road from the i-th city to the j-th and d_i β₯ d_j;
3. Stop traveling.
Since the government of Berland does not want all people to come to the capital, so Polycarp no more than once can take the second action from the list. in other words, he can perform the second action 0 or 1 time during his journey. Polycarp, on the other hand, wants to be as close to the capital as possible.
<image>
For example, if n = 6 and the cities are connected, as in the picture above, then Polycarp could have made the following travels (not all possible options):
* 2 β 5 β 1 β 2 β 5;
* 3 β 6 β 2;
* 1 β 3 β 6 β 2 β 5.
Polycarp wants for each starting city i to find out how close he can get to the capital. More formally: he wants to find the minimal value of d_j that Polycarp can get from the city i to the city j according to the rules described above.
Input
The first line contains one integer t (1 β€ t β€ 10^4) β the number of test cases. Then t test cases follow.
Each test case is preceded by an empty line.
The first line of each test case contains two integers n (2 β€ n β€ 2 β
10^5) and m (1 β€ m β€ 2 β
10^5) β number of cities and roads, respectively.
This is followed by m lines describing the roads. Each road is characterized by two integers u and v (1 β€ u, v β€ n, u β v) β the numbers of cities connected by a one-way road.
It is guaranteed that the sums of n and m over all test cases do not exceed 2 β
10^5.
It is guaranteed that for each pair of different cities (u, v) there is at most one road from u to v (but a pair of roads from u to v and from v to u β is valid).
It is guaranteed that there is a path from the capital to all cities.
Output
For each test case, on a separate line output n numbers, the i-th of which is equal to the minimum possible distance from the capital to the city where Polycarp ended his journey.
Example
Input
3
6 7
1 2
1 3
2 5
2 4
5 1
3 6
6 2
2 2
1 2
2 1
6 8
1 2
1 5
2 6
6 1
2 3
3 4
4 2
5 4
Output
0 0 1 2 0 1
0 0
0 0 2 1 1 0
Tags: dfs and similar, dp, graphs, shortest paths
Correct Solution:
```
from queue import Queue
class Node:
def __init__(self, idx, d = -1):
self.d = d
self.idx = idx
self.par = []
t = int(input())
for _ in range(t):
dkk = input()
c, eds = tuple([int(x) for x in input().split()])
adl = [[] for i in range(c + 1)]
for z in range(eds):
u, v = tuple([int(x) for x in input().split()])
adl[u - 1].append(v - 1)
nodes = [Node(i) for i in range(c)]
q = Queue()
q.put(0)
ans = [10 ** 9] * c
ans[0] = nodes[0].d = 0
def rewind(x, dis):
if ans[x] > dis:
ans[x] = dis
else:
return
for sdd in nodes[x].par:
rewind(sdd, dis)
while q.qsize():
front = q.get()
# print('fr', front)
for e in adl[front]:
# print('e', e)
if nodes[e].d == -1:
q.put(e)
nodes[e].d = nodes[front].d + 1
nodes[e].par.append(front)
ans[e] = min(ans[e], nodes[e].d)
elif nodes[e].d > nodes[front].d:
nodes[e].par.append(front)
ans[e] = min(ans[e], nodes[e].d)
else:
rewind(front, nodes[e].d)
for e in ans:
print(e, end=' ')
print()
```
| 90,351 |
Provide tags and a correct Python 3 solution for this coding contest problem.
There are n cities in Berland. The city numbered 1 is the capital. Some pairs of cities are connected by a one-way road of length 1.
Before the trip, Polycarp for each city found out the value of d_i β the shortest distance from the capital (the 1-st city) to the i-th city.
Polycarp begins his journey in the city with number s and, being in the i-th city, chooses one of the following actions:
1. Travel from the i-th city to the j-th city if there is a road from the i-th city to the j-th and d_i < d_j;
2. Travel from the i-th city to the j-th city if there is a road from the i-th city to the j-th and d_i β₯ d_j;
3. Stop traveling.
Since the government of Berland does not want all people to come to the capital, so Polycarp no more than once can take the second action from the list. in other words, he can perform the second action 0 or 1 time during his journey. Polycarp, on the other hand, wants to be as close to the capital as possible.
<image>
For example, if n = 6 and the cities are connected, as in the picture above, then Polycarp could have made the following travels (not all possible options):
* 2 β 5 β 1 β 2 β 5;
* 3 β 6 β 2;
* 1 β 3 β 6 β 2 β 5.
Polycarp wants for each starting city i to find out how close he can get to the capital. More formally: he wants to find the minimal value of d_j that Polycarp can get from the city i to the city j according to the rules described above.
Input
The first line contains one integer t (1 β€ t β€ 10^4) β the number of test cases. Then t test cases follow.
Each test case is preceded by an empty line.
The first line of each test case contains two integers n (2 β€ n β€ 2 β
10^5) and m (1 β€ m β€ 2 β
10^5) β number of cities and roads, respectively.
This is followed by m lines describing the roads. Each road is characterized by two integers u and v (1 β€ u, v β€ n, u β v) β the numbers of cities connected by a one-way road.
It is guaranteed that the sums of n and m over all test cases do not exceed 2 β
10^5.
It is guaranteed that for each pair of different cities (u, v) there is at most one road from u to v (but a pair of roads from u to v and from v to u β is valid).
It is guaranteed that there is a path from the capital to all cities.
Output
For each test case, on a separate line output n numbers, the i-th of which is equal to the minimum possible distance from the capital to the city where Polycarp ended his journey.
Example
Input
3
6 7
1 2
1 3
2 5
2 4
5 1
3 6
6 2
2 2
1 2
2 1
6 8
1 2
1 5
2 6
6 1
2 3
3 4
4 2
5 4
Output
0 0 1 2 0 1
0 0
0 0 2 1 1 0
Tags: dfs and similar, dp, graphs, shortest paths
Correct Solution:
```
import sys
input=sys.stdin.buffer.readline #FOR READING PURE INTEGER INPUTS (space separation ok)
from queue import deque
from types import GeneratorType
def bootstrap(f, stack=[]):
def wrappedfunc(*args, **kwargs):
if stack:
return f(*args, **kwargs)
else:
to = f(*args, **kwargs)
while True:
if type(to) is GeneratorType:
stack.append(to)
to = next(to)
else:
stack.pop()
if not stack:
break
to = stack[-1].send(to)
return to
return wrappedfunc
def multiLineArrayOfArraysPrint(arr):
print('\n'.join([' '.join([str(x) for x in y]) for y in arr]))
@bootstrap
def dp(node,nMove2): #return the min d value possible starting from node with at most nMove2 move 2s
# print('node:{} nMove2:{}'.format(node,nMove2))
if memo[node][nMove2]==None:
ans=d[node]
for nex in adj[node]:
if d[node]<d[nex]: #nMove doesnt change
ans=min(ans, (yield dp(nex,nMove2)))
else: #nMove2 increases by 1
if nMove2+1<=1:
ans=min(ans, (yield dp(nex,nMove2+1)))
memo[node][nMove2]=ans
yield memo[node][nMove2]
t=int(input())
allAns=[]
for _ in range(t):
input() # for the empty line
n,m=[int(x) for x in input().split()]
adj=[[] for _ in range(n+1)]
for __ in range(m):
u,v=[int(x) for x in input().split()]
adj[u].append(v)
d=[0 for _ in range(n+1)]
visited=[False for _ in range(n+1)]
q=deque() #[road,distance from capital]
q.append([1,0])
while q:
road,distance=q.popleft()
if visited[road]==True:
continue
d[road]=distance
visited[road]=True
for nex in adj[road]:
if visited[nex]==False:
q.append([nex,distance+1])
memo=[[None,None] for __ in range(n+1)]
ans=[]
for i in range(1,n+1):
ans.append(dp(i,0))
allAns.append(ans)
multiLineArrayOfArraysPrint(allAns)
```
| 90,352 |
Provide tags and a correct Python 3 solution for this coding contest problem.
There are n cities in Berland. The city numbered 1 is the capital. Some pairs of cities are connected by a one-way road of length 1.
Before the trip, Polycarp for each city found out the value of d_i β the shortest distance from the capital (the 1-st city) to the i-th city.
Polycarp begins his journey in the city with number s and, being in the i-th city, chooses one of the following actions:
1. Travel from the i-th city to the j-th city if there is a road from the i-th city to the j-th and d_i < d_j;
2. Travel from the i-th city to the j-th city if there is a road from the i-th city to the j-th and d_i β₯ d_j;
3. Stop traveling.
Since the government of Berland does not want all people to come to the capital, so Polycarp no more than once can take the second action from the list. in other words, he can perform the second action 0 or 1 time during his journey. Polycarp, on the other hand, wants to be as close to the capital as possible.
<image>
For example, if n = 6 and the cities are connected, as in the picture above, then Polycarp could have made the following travels (not all possible options):
* 2 β 5 β 1 β 2 β 5;
* 3 β 6 β 2;
* 1 β 3 β 6 β 2 β 5.
Polycarp wants for each starting city i to find out how close he can get to the capital. More formally: he wants to find the minimal value of d_j that Polycarp can get from the city i to the city j according to the rules described above.
Input
The first line contains one integer t (1 β€ t β€ 10^4) β the number of test cases. Then t test cases follow.
Each test case is preceded by an empty line.
The first line of each test case contains two integers n (2 β€ n β€ 2 β
10^5) and m (1 β€ m β€ 2 β
10^5) β number of cities and roads, respectively.
This is followed by m lines describing the roads. Each road is characterized by two integers u and v (1 β€ u, v β€ n, u β v) β the numbers of cities connected by a one-way road.
It is guaranteed that the sums of n and m over all test cases do not exceed 2 β
10^5.
It is guaranteed that for each pair of different cities (u, v) there is at most one road from u to v (but a pair of roads from u to v and from v to u β is valid).
It is guaranteed that there is a path from the capital to all cities.
Output
For each test case, on a separate line output n numbers, the i-th of which is equal to the minimum possible distance from the capital to the city where Polycarp ended his journey.
Example
Input
3
6 7
1 2
1 3
2 5
2 4
5 1
3 6
6 2
2 2
1 2
2 1
6 8
1 2
1 5
2 6
6 1
2 3
3 4
4 2
5 4
Output
0 0 1 2 0 1
0 0
0 0 2 1 1 0
Tags: dfs and similar, dp, graphs, shortest paths
Correct Solution:
```
# https://codeforces.com/problemset/problem/1472/G
from collections import defaultdict, deque
import sys
input = sys.stdin.readline
def get_distances(graph):
q = deque()
q.append(1)
q.append(None)
d, distances = 0, {}
while len(q) > 1:
u = q.popleft()
if u is None:
d += 1
q.append(None)
continue
if u in distances:
continue
distances[u] = d
for v in graph[u]:
if v not in distances:
q.append(v)
return distances
def bfs(starting_vertex, graph, visited, dists):
q = deque()
q.append((starting_vertex, None))
q.append((None, None))
d, nodes_at_d = 0, defaultdict(list)
while len(q) > 1:
u, parent = q.popleft()
if u is None:
d += 1
q.append((None, None))
continue
nodes_at_d[d].append((u, parent))
if u in visited:
continue
visited.add(u)
for v in graph[u]:
if v not in visited:
q.append((v, u))
else:
dists[u] = min(dists[u], dists[v])
while d >= 0:
for u, parent in nodes_at_d[d]:
if parent is not None:
dists[parent] = min(dists[parent], dists[u])
d -= 1
t = int(input())
for _ in range(t):
_ = input()
n, m = (int(i) for i in input().split(' '))
graph = defaultdict(list)
for _ in range(m):
u, v = (int(i) for i in input().split(' '))
graph[u].append(v)
dists = get_distances(graph)
new_graph = defaultdict(list)
for u in graph:
while graph[u]:
v = graph[u].pop()
if dists[v] > dists[u]:
new_graph[u].append(v)
new_graph[u+n].append(v+n)
else:
new_graph[u].append(v+n)
for u in range(1, n + 1):
dists[u + n] = dists[u]
visited = set()
bfs(1, new_graph, visited, dists)
for u in range(1, n + 1):
print(min(dists[u], dists[u + n]), end=' ')
print()
```
| 90,353 |
Provide tags and a correct Python 3 solution for this coding contest problem.
There are n cities in Berland. The city numbered 1 is the capital. Some pairs of cities are connected by a one-way road of length 1.
Before the trip, Polycarp for each city found out the value of d_i β the shortest distance from the capital (the 1-st city) to the i-th city.
Polycarp begins his journey in the city with number s and, being in the i-th city, chooses one of the following actions:
1. Travel from the i-th city to the j-th city if there is a road from the i-th city to the j-th and d_i < d_j;
2. Travel from the i-th city to the j-th city if there is a road from the i-th city to the j-th and d_i β₯ d_j;
3. Stop traveling.
Since the government of Berland does not want all people to come to the capital, so Polycarp no more than once can take the second action from the list. in other words, he can perform the second action 0 or 1 time during his journey. Polycarp, on the other hand, wants to be as close to the capital as possible.
<image>
For example, if n = 6 and the cities are connected, as in the picture above, then Polycarp could have made the following travels (not all possible options):
* 2 β 5 β 1 β 2 β 5;
* 3 β 6 β 2;
* 1 β 3 β 6 β 2 β 5.
Polycarp wants for each starting city i to find out how close he can get to the capital. More formally: he wants to find the minimal value of d_j that Polycarp can get from the city i to the city j according to the rules described above.
Input
The first line contains one integer t (1 β€ t β€ 10^4) β the number of test cases. Then t test cases follow.
Each test case is preceded by an empty line.
The first line of each test case contains two integers n (2 β€ n β€ 2 β
10^5) and m (1 β€ m β€ 2 β
10^5) β number of cities and roads, respectively.
This is followed by m lines describing the roads. Each road is characterized by two integers u and v (1 β€ u, v β€ n, u β v) β the numbers of cities connected by a one-way road.
It is guaranteed that the sums of n and m over all test cases do not exceed 2 β
10^5.
It is guaranteed that for each pair of different cities (u, v) there is at most one road from u to v (but a pair of roads from u to v and from v to u β is valid).
It is guaranteed that there is a path from the capital to all cities.
Output
For each test case, on a separate line output n numbers, the i-th of which is equal to the minimum possible distance from the capital to the city where Polycarp ended his journey.
Example
Input
3
6 7
1 2
1 3
2 5
2 4
5 1
3 6
6 2
2 2
1 2
2 1
6 8
1 2
1 5
2 6
6 1
2 3
3 4
4 2
5 4
Output
0 0 1 2 0 1
0 0
0 0 2 1 1 0
Tags: dfs and similar, dp, graphs, shortest paths
Correct Solution:
```
import sys
input = sys.stdin.readline
sys.setrecursionlimit(100000)
from collections import deque
class Graph(object):
"""docstring for Graph"""
def __init__(self,n,d): # Number of nodes and d is True if directed
self.n = n
self.graph = [[] for i in range(n)]
self.parent = [-1 for i in range(n)]
self.directed = d
def addEdge(self,x,y):
self.graph[x].append(y)
if not self.directed:
self.graph[y].append(x)
def bfs(self, root): # NORMAL BFS
queue = [root]
queue = deque(queue)
vis = [0]*self.n
dist = [0]*self.n
while len(queue)!=0:
element = queue.popleft()
vis[element] = 1
for i in self.graph[element]:
if vis[i]==0:
queue.append(i)
self.parent[i] = element
dist[i] = dist[element] + 1
vis[i] = 1
return dist
def dfs(self, root, minn): # Iterative DFS
ans = [i for i in minn]
stack=[root]
vis=[0]*self.n
stack2=[]
while len(stack)!=0: # INITIAL TRAVERSAL
element = stack.pop()
if vis[element]:
continue
vis[element] = 1
stack2.append(element)
for i in self.graph[element]:
if vis[i]==0:
self.parent[i] = element
stack.append(i)
# print (stack2)
while len(stack2)!=0: # BACKTRACING. Modify the loop according to the question
element = stack2.pop()
m = minn[element]
for i in self.graph[element]:
if i!=self.parent[element]:
m = min(m, ans[i])
ans[element] = m
return ans
def shortestpath(self, source, dest): # Calculate Shortest Path between two nodes
self.bfs(source)
path = [dest]
while self.parent[path[-1]]!=-1:
path.append(parent[path[-1]])
return path[::-1]
def detect_cycle(self):
indeg = [0]*self.n
for i in range(self.n):
for j in self.graph[i]:
indeg[j] += 1
q = deque()
vis = 0
for i in range(self.n):
if indeg[i]==0:
q.append(i)
while len(q)!=0:
e = q.popleft()
vis += 1
for i in self.graph[e]:
indeg[i] -= 1
if indeg[i]==0:
q.append(i)
if vis!=self.n:
return True
return False
def reroot(self, root, ans):
stack = [root]
vis = [0]*n
while len(stack)!=0:
e = stack[-1]
if vis[e]:
stack.pop()
# Reverse_The_Change()
continue
vis[e] = 1
for i in graph[e]:
if not vis[e]:
stack.append(i)
if self.parent[e]==-1:
continue
# Change_The_Answers()
def eulertour(self, root):
stack=[root]
t = []
while len(stack)!=0:
element = stack[-1]
if vis[element]:
t.append(stack.pop())
continue
t.append(element)
vis[element] = 1
for i in self.graph[element]:
if not vis[i]:
stack.append(i)
return t
for nt in range(int(input())):
input()
n, m = map(int, input().split())
adj = [[] for xy in range(n)]
for xy in range(m):
u, v = map(lambda x: int(x) - 1, input().split())
adj[u].append(v)
dis = [-1] * n
dis[0] = 0
que = [0]
for i in range(n):
u = que[i]
for v in adj[u]:
if dis[v] == -1:
dis[v] = dis[u] + 1
que.append(v)
ans = [0] * n
for u in sorted([i for i in range(n)], key=lambda x: dis[x], reverse=True):
ans[u] = dis[u]
for v in adj[u]:
if dis[u] >= dis[v]:
ans[u] = min(ans[u], dis[v])
else:
ans[u] = min(ans[u], ans[v])
print(*ans)
```
| 90,354 |
Provide tags and a correct Python 3 solution for this coding contest problem.
There are n cities in Berland. The city numbered 1 is the capital. Some pairs of cities are connected by a one-way road of length 1.
Before the trip, Polycarp for each city found out the value of d_i β the shortest distance from the capital (the 1-st city) to the i-th city.
Polycarp begins his journey in the city with number s and, being in the i-th city, chooses one of the following actions:
1. Travel from the i-th city to the j-th city if there is a road from the i-th city to the j-th and d_i < d_j;
2. Travel from the i-th city to the j-th city if there is a road from the i-th city to the j-th and d_i β₯ d_j;
3. Stop traveling.
Since the government of Berland does not want all people to come to the capital, so Polycarp no more than once can take the second action from the list. in other words, he can perform the second action 0 or 1 time during his journey. Polycarp, on the other hand, wants to be as close to the capital as possible.
<image>
For example, if n = 6 and the cities are connected, as in the picture above, then Polycarp could have made the following travels (not all possible options):
* 2 β 5 β 1 β 2 β 5;
* 3 β 6 β 2;
* 1 β 3 β 6 β 2 β 5.
Polycarp wants for each starting city i to find out how close he can get to the capital. More formally: he wants to find the minimal value of d_j that Polycarp can get from the city i to the city j according to the rules described above.
Input
The first line contains one integer t (1 β€ t β€ 10^4) β the number of test cases. Then t test cases follow.
Each test case is preceded by an empty line.
The first line of each test case contains two integers n (2 β€ n β€ 2 β
10^5) and m (1 β€ m β€ 2 β
10^5) β number of cities and roads, respectively.
This is followed by m lines describing the roads. Each road is characterized by two integers u and v (1 β€ u, v β€ n, u β v) β the numbers of cities connected by a one-way road.
It is guaranteed that the sums of n and m over all test cases do not exceed 2 β
10^5.
It is guaranteed that for each pair of different cities (u, v) there is at most one road from u to v (but a pair of roads from u to v and from v to u β is valid).
It is guaranteed that there is a path from the capital to all cities.
Output
For each test case, on a separate line output n numbers, the i-th of which is equal to the minimum possible distance from the capital to the city where Polycarp ended his journey.
Example
Input
3
6 7
1 2
1 3
2 5
2 4
5 1
3 6
6 2
2 2
1 2
2 1
6 8
1 2
1 5
2 6
6 1
2 3
3 4
4 2
5 4
Output
0 0 1 2 0 1
0 0
0 0 2 1 1 0
Tags: dfs and similar, dp, graphs, shortest paths
Correct Solution:
```
from collections import deque
import os
import sys
from io import BytesIO, IOBase
from types import GeneratorType
from collections import defaultdict
BUFSIZE = 8192
class FastIO(IOBase):
newlines = 0
def __init__(self, file):
self._fd = file.fileno()
self.buffer = BytesIO()
self.writable = "x" in file.mode or "r" not in file.mode
self.write = self.buffer.write if self.writable else None
def read(self):
while True:
b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
if not b:
break
ptr = self.buffer.tell()
self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr)
self.newlines = 0
return self.buffer.read()
def readline(self):
while self.newlines == 0:
b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
self.newlines = b.count(b"\n") + (not b)
ptr = self.buffer.tell()
self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr)
self.newlines -= 1
return self.buffer.readline()
def flush(self):
if self.writable:
os.write(self._fd, self.buffer.getvalue())
self.buffer.truncate(0), self.buffer.seek(0)
class IOWrapper(IOBase):
def __init__(self, file):
self.buffer = FastIO(file)
self.flush = self.buffer.flush
self.writable = self.buffer.writable
self.write = lambda s: self.buffer.write(s.encode("ascii"))
self.read = lambda: self.buffer.read().decode("ascii")
self.readline = lambda: self.buffer.readline().decode("ascii")
sys.stdin, sys.stdout = IOWrapper(sys.stdin), IOWrapper(sys.stdout)
input = lambda: sys.stdin.readline().rstrip("\r\n")
sys.setrecursionlimit(2*10**5)
def bootstrap(f, stack=[]):
def wrappedfunc(*args, **kwargs):
if stack:
return f(*args, **kwargs)
else:
to = f(*args, **kwargs)
while True:
if type(to) is GeneratorType:
stack.append(to)
to = next(to)
else:
stack.pop()
if not stack:
break
to = stack[-1].send(to)
return to
return wrappedfunc
@bootstrap
def dfs(u):
vis[u]=1
for j in adj[u]:
if dist[u]>=dist[j]:
continue
if not vis[j]:
yield dfs(j)
ans[u]=min(ans[u],ans[j])
yield
t=int(input())
for i in range(t):
p=input()
n,m=map(int,input().split())
adj=[[] for j in range(n+1)]
for j in range(m):
u,v=map(int,input().split())
adj[u].append(v)
dist=[float("inf")]*(n+1)
dist[1]=0
q=deque()
q.append(1)
vis=[0]*(n+1)
vis[1]=1
while(q):
u=q.popleft()
for j in adj[u]:
if not vis[j]:
dist[j]=1+dist[u]
vis[j]=1
q.append(j)
ans=[float("inf")]*(n+1)
for j in range(1,n+1):
vis[j]=0
ans[j]=dist[j]
for v in adj[j]:
ans[j]=min(ans[j],dist[v])
for i in range(1,n+1):
if not vis[i]:
dfs(i)
ans.pop(0)
print(*ans)
```
| 90,355 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
There are n cities in Berland. The city numbered 1 is the capital. Some pairs of cities are connected by a one-way road of length 1.
Before the trip, Polycarp for each city found out the value of d_i β the shortest distance from the capital (the 1-st city) to the i-th city.
Polycarp begins his journey in the city with number s and, being in the i-th city, chooses one of the following actions:
1. Travel from the i-th city to the j-th city if there is a road from the i-th city to the j-th and d_i < d_j;
2. Travel from the i-th city to the j-th city if there is a road from the i-th city to the j-th and d_i β₯ d_j;
3. Stop traveling.
Since the government of Berland does not want all people to come to the capital, so Polycarp no more than once can take the second action from the list. in other words, he can perform the second action 0 or 1 time during his journey. Polycarp, on the other hand, wants to be as close to the capital as possible.
<image>
For example, if n = 6 and the cities are connected, as in the picture above, then Polycarp could have made the following travels (not all possible options):
* 2 β 5 β 1 β 2 β 5;
* 3 β 6 β 2;
* 1 β 3 β 6 β 2 β 5.
Polycarp wants for each starting city i to find out how close he can get to the capital. More formally: he wants to find the minimal value of d_j that Polycarp can get from the city i to the city j according to the rules described above.
Input
The first line contains one integer t (1 β€ t β€ 10^4) β the number of test cases. Then t test cases follow.
Each test case is preceded by an empty line.
The first line of each test case contains two integers n (2 β€ n β€ 2 β
10^5) and m (1 β€ m β€ 2 β
10^5) β number of cities and roads, respectively.
This is followed by m lines describing the roads. Each road is characterized by two integers u and v (1 β€ u, v β€ n, u β v) β the numbers of cities connected by a one-way road.
It is guaranteed that the sums of n and m over all test cases do not exceed 2 β
10^5.
It is guaranteed that for each pair of different cities (u, v) there is at most one road from u to v (but a pair of roads from u to v and from v to u β is valid).
It is guaranteed that there is a path from the capital to all cities.
Output
For each test case, on a separate line output n numbers, the i-th of which is equal to the minimum possible distance from the capital to the city where Polycarp ended his journey.
Example
Input
3
6 7
1 2
1 3
2 5
2 4
5 1
3 6
6 2
2 2
1 2
2 1
6 8
1 2
1 5
2 6
6 1
2 3
3 4
4 2
5 4
Output
0 0 1 2 0 1
0 0
0 0 2 1 1 0
Submitted Solution:
```
import sys
from collections import deque
input = sys.stdin.buffer.readline
for _ in range(int(input())):
unko = input()
n,m = map(int,input().split())
pre_edge = [[] for i in range(n)]
for i in range(m):
u,v = map(int,input().split())
pre_edge[u-1].append(v-1)
deq = deque([0])
dist = [10**17 for i in range(n)]
dist[0] = 0
edge = [[] for i in range(n)]
while deq:
v = deq.popleft()
for nv in pre_edge[v]:
if dist[nv] > dist[v] + 1:
dist[nv] = dist[v] + 1
edge[v].append(nv)
deq.append(nv)
#print(dist)
dist_sort = [[] for i in range(n)]
for i in range(n):
dist_sort[dist[i]].append(i)
ans = [dist[i] for i in range(n)]
for d in range(n-1,-1,-1):
for v in dist_sort[d]:
for nv in pre_edge[v]:
if dist[nv] > dist[v]:
ans[v] = min(ans[v],ans[nv])
else:
ans[v] = min(dist[nv],ans[v])
print(*ans)
```
Yes
| 90,356 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
There are n cities in Berland. The city numbered 1 is the capital. Some pairs of cities are connected by a one-way road of length 1.
Before the trip, Polycarp for each city found out the value of d_i β the shortest distance from the capital (the 1-st city) to the i-th city.
Polycarp begins his journey in the city with number s and, being in the i-th city, chooses one of the following actions:
1. Travel from the i-th city to the j-th city if there is a road from the i-th city to the j-th and d_i < d_j;
2. Travel from the i-th city to the j-th city if there is a road from the i-th city to the j-th and d_i β₯ d_j;
3. Stop traveling.
Since the government of Berland does not want all people to come to the capital, so Polycarp no more than once can take the second action from the list. in other words, he can perform the second action 0 or 1 time during his journey. Polycarp, on the other hand, wants to be as close to the capital as possible.
<image>
For example, if n = 6 and the cities are connected, as in the picture above, then Polycarp could have made the following travels (not all possible options):
* 2 β 5 β 1 β 2 β 5;
* 3 β 6 β 2;
* 1 β 3 β 6 β 2 β 5.
Polycarp wants for each starting city i to find out how close he can get to the capital. More formally: he wants to find the minimal value of d_j that Polycarp can get from the city i to the city j according to the rules described above.
Input
The first line contains one integer t (1 β€ t β€ 10^4) β the number of test cases. Then t test cases follow.
Each test case is preceded by an empty line.
The first line of each test case contains two integers n (2 β€ n β€ 2 β
10^5) and m (1 β€ m β€ 2 β
10^5) β number of cities and roads, respectively.
This is followed by m lines describing the roads. Each road is characterized by two integers u and v (1 β€ u, v β€ n, u β v) β the numbers of cities connected by a one-way road.
It is guaranteed that the sums of n and m over all test cases do not exceed 2 β
10^5.
It is guaranteed that for each pair of different cities (u, v) there is at most one road from u to v (but a pair of roads from u to v and from v to u β is valid).
It is guaranteed that there is a path from the capital to all cities.
Output
For each test case, on a separate line output n numbers, the i-th of which is equal to the minimum possible distance from the capital to the city where Polycarp ended his journey.
Example
Input
3
6 7
1 2
1 3
2 5
2 4
5 1
3 6
6 2
2 2
1 2
2 1
6 8
1 2
1 5
2 6
6 1
2 3
3 4
4 2
5 4
Output
0 0 1 2 0 1
0 0
0 0 2 1 1 0
Submitted Solution:
```
import os
import sys
from io import BytesIO, IOBase
# region fastio
BUFSIZE = 8192
class FastIO(IOBase):
def __init__(self, file):
self.newlines = 0
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()
# --------------------------------------------------------------------
def RL(): return map(int, sys.stdin.readline().split())
def RLL(): return list(map(int, sys.stdin.readline().split()))
def N(): return int(input())
def S(): return input().strip()
def print_list(l): print(' '.join(map(str, l)))
# sys.setrecursionlimit(200000)
# import random
# from functools import reduce
# from functools import lru_cache
# from heapq import *
# from collections import deque as dq
# from math import ceil
# import bisect as bs
# from collections import Counter
# from collections import defaultdict as dc
for i in range(N()):
input()
n, m = RL()
dic = [[] for _ in range(n)]
for _ in range(m):
u, v = RL()
dic[u - 1].append(v - 1)
dist = [-1] * n
dist[0] = 0
now = [0]
k = 1
while now:
nex = []
for u in now:
for v in dic[u]:
if dist[v] == -1:
dist[v] = k
nex.append(v)
now = nex
k += 1
deep = sorted([i for i in range(n)], key=lambda x:dist[x], reverse=True)
res = [n] * n
for u in deep:
res[u] = dist[u]
for v in dic[u]:
t = dist[v] if dist[v] <= dist[u] else res[v]
if t < res[u]: res[u] = t
print_list(res)
```
Yes
| 90,357 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
There are n cities in Berland. The city numbered 1 is the capital. Some pairs of cities are connected by a one-way road of length 1.
Before the trip, Polycarp for each city found out the value of d_i β the shortest distance from the capital (the 1-st city) to the i-th city.
Polycarp begins his journey in the city with number s and, being in the i-th city, chooses one of the following actions:
1. Travel from the i-th city to the j-th city if there is a road from the i-th city to the j-th and d_i < d_j;
2. Travel from the i-th city to the j-th city if there is a road from the i-th city to the j-th and d_i β₯ d_j;
3. Stop traveling.
Since the government of Berland does not want all people to come to the capital, so Polycarp no more than once can take the second action from the list. in other words, he can perform the second action 0 or 1 time during his journey. Polycarp, on the other hand, wants to be as close to the capital as possible.
<image>
For example, if n = 6 and the cities are connected, as in the picture above, then Polycarp could have made the following travels (not all possible options):
* 2 β 5 β 1 β 2 β 5;
* 3 β 6 β 2;
* 1 β 3 β 6 β 2 β 5.
Polycarp wants for each starting city i to find out how close he can get to the capital. More formally: he wants to find the minimal value of d_j that Polycarp can get from the city i to the city j according to the rules described above.
Input
The first line contains one integer t (1 β€ t β€ 10^4) β the number of test cases. Then t test cases follow.
Each test case is preceded by an empty line.
The first line of each test case contains two integers n (2 β€ n β€ 2 β
10^5) and m (1 β€ m β€ 2 β
10^5) β number of cities and roads, respectively.
This is followed by m lines describing the roads. Each road is characterized by two integers u and v (1 β€ u, v β€ n, u β v) β the numbers of cities connected by a one-way road.
It is guaranteed that the sums of n and m over all test cases do not exceed 2 β
10^5.
It is guaranteed that for each pair of different cities (u, v) there is at most one road from u to v (but a pair of roads from u to v and from v to u β is valid).
It is guaranteed that there is a path from the capital to all cities.
Output
For each test case, on a separate line output n numbers, the i-th of which is equal to the minimum possible distance from the capital to the city where Polycarp ended his journey.
Example
Input
3
6 7
1 2
1 3
2 5
2 4
5 1
3 6
6 2
2 2
1 2
2 1
6 8
1 2
1 5
2 6
6 1
2 3
3 4
4 2
5 4
Output
0 0 1 2 0 1
0 0
0 0 2 1 1 0
Submitted Solution:
```
import os,io
input=io.BytesIO(os.read(0,os.fstat(0).st_size)).readline
import heapq
INF=10**9
def Dijkstra(graph, start):
dist=[INF]*len(graph)
parent=[INF]*len(graph)
queue=[(0, start)]
while queue:
path_len, v=heapq.heappop(queue)
if dist[v]==INF:
dist[v]=path_len
for w in graph[v]:
if dist[w[0]]==INF:
parent[w[0]]=v
heapq.heappush(queue, (dist[v]+w[1], w[0]))
return (dist,parent)
t=int(input())
for _ in range(t):
input()
n,m=map(int,input().split())
graph=[]
for i in range(n):
graph.append([])
edges=[]
for i in range(m):
x,y=map(int,input().split())
graph[x-1].append([y-1,1])
edges.append([x-1,y-1])
dist,parent=Dijkstra(graph,0)
visited=set()
mindist=[INF]*n
for i in range(n):
mindist[i]=dist[i]
for j in graph[i]:
mindist[i]=min(mindist[i],dist[j[0]])
graph2=[]
for i in range(n):
graph2.append([])
edges2=[]
for edge in edges:
x=edge[0]
y=edge[1]
if dist[y]>dist[x]:
graph2[x].append(y)
edges2.append([x,y])
vertices=[]
for i in range(n):
vertices.append([dist[i],i])
vertices.sort()
vertices.reverse()
for i in range(n):
index=vertices[i][1]
for j in graph2[index]:
mindist[index]=min(mindist[index],mindist[j])
for i in range(n):
mindist[i]=str(mindist[i])
print(' '.join(mindist))
```
Yes
| 90,358 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
There are n cities in Berland. The city numbered 1 is the capital. Some pairs of cities are connected by a one-way road of length 1.
Before the trip, Polycarp for each city found out the value of d_i β the shortest distance from the capital (the 1-st city) to the i-th city.
Polycarp begins his journey in the city with number s and, being in the i-th city, chooses one of the following actions:
1. Travel from the i-th city to the j-th city if there is a road from the i-th city to the j-th and d_i < d_j;
2. Travel from the i-th city to the j-th city if there is a road from the i-th city to the j-th and d_i β₯ d_j;
3. Stop traveling.
Since the government of Berland does not want all people to come to the capital, so Polycarp no more than once can take the second action from the list. in other words, he can perform the second action 0 or 1 time during his journey. Polycarp, on the other hand, wants to be as close to the capital as possible.
<image>
For example, if n = 6 and the cities are connected, as in the picture above, then Polycarp could have made the following travels (not all possible options):
* 2 β 5 β 1 β 2 β 5;
* 3 β 6 β 2;
* 1 β 3 β 6 β 2 β 5.
Polycarp wants for each starting city i to find out how close he can get to the capital. More formally: he wants to find the minimal value of d_j that Polycarp can get from the city i to the city j according to the rules described above.
Input
The first line contains one integer t (1 β€ t β€ 10^4) β the number of test cases. Then t test cases follow.
Each test case is preceded by an empty line.
The first line of each test case contains two integers n (2 β€ n β€ 2 β
10^5) and m (1 β€ m β€ 2 β
10^5) β number of cities and roads, respectively.
This is followed by m lines describing the roads. Each road is characterized by two integers u and v (1 β€ u, v β€ n, u β v) β the numbers of cities connected by a one-way road.
It is guaranteed that the sums of n and m over all test cases do not exceed 2 β
10^5.
It is guaranteed that for each pair of different cities (u, v) there is at most one road from u to v (but a pair of roads from u to v and from v to u β is valid).
It is guaranteed that there is a path from the capital to all cities.
Output
For each test case, on a separate line output n numbers, the i-th of which is equal to the minimum possible distance from the capital to the city where Polycarp ended his journey.
Example
Input
3
6 7
1 2
1 3
2 5
2 4
5 1
3 6
6 2
2 2
1 2
2 1
6 8
1 2
1 5
2 6
6 1
2 3
3 4
4 2
5 4
Output
0 0 1 2 0 1
0 0
0 0 2 1 1 0
Submitted Solution:
```
import sys
input = sys.stdin.readline
from collections import deque
class Graph:
def __init__(self, N, M=False):
self.V = N
if M: self.E = M
self.edge = [[] for _ in range(self.V)]
self.visited = [False]*self.V
def add_edges(self, ind=1, bi=False):
self.edges = [0]*self.E
for i in range(self.E):
a,b = map(int, input().split())
a -= ind; b -= ind
self.edge[a].append(b)
self.edges[i] = (a,b)
if bi: self.edge[b].append(a)
def add_edge(self, a, b, bi=False):
self.edge[a].append(b)
if bi: self.edge[b].append(a)
def bfs(self, start):
d = deque([start])
self.min_cost = [-1]*self.V; self.min_cost[start]=0
while len(d)>0:
v = d.popleft()
for w in self.edge[v]:
if self.min_cost[w]==-1:
self.min_cost[w]=self.min_cost[v]+1
d.append(w)
return
def dfs(self, start, cost, N):
stack = deque([start])
self.visited[start] = True
ans[start] = min(ans[start], cost)
while stack:
v = stack.pop()
for u in self.edge[v]:
if self.visited[u]: continue
stack.append(u)
self.visited[u] = True
ans[u%N] = min(ans[u%N], cost)
T = int(input())
for t in range(T):
input()
N, M = map(int, input().split())
G = Graph(N,M)
G.add_edges(ind=1, bi=False)
G.bfs(0)
costs = []
for i,cos in enumerate(G.min_cost):
costs.append((cos,i))
costs.sort()
G2 = Graph(N*2)
for a,b in G.edges:
if G.min_cost[b]>G.min_cost[a]:
G2.add_edge(b,a); G2.add_edge(N+b,N+a)
else:
G2.add_edge(b,a+N)
ans = [N]*N
for cos,i in costs:
G2.dfs(i, cos, N)
print(*ans, sep=' ')
```
Yes
| 90,359 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
There are n cities in Berland. The city numbered 1 is the capital. Some pairs of cities are connected by a one-way road of length 1.
Before the trip, Polycarp for each city found out the value of d_i β the shortest distance from the capital (the 1-st city) to the i-th city.
Polycarp begins his journey in the city with number s and, being in the i-th city, chooses one of the following actions:
1. Travel from the i-th city to the j-th city if there is a road from the i-th city to the j-th and d_i < d_j;
2. Travel from the i-th city to the j-th city if there is a road from the i-th city to the j-th and d_i β₯ d_j;
3. Stop traveling.
Since the government of Berland does not want all people to come to the capital, so Polycarp no more than once can take the second action from the list. in other words, he can perform the second action 0 or 1 time during his journey. Polycarp, on the other hand, wants to be as close to the capital as possible.
<image>
For example, if n = 6 and the cities are connected, as in the picture above, then Polycarp could have made the following travels (not all possible options):
* 2 β 5 β 1 β 2 β 5;
* 3 β 6 β 2;
* 1 β 3 β 6 β 2 β 5.
Polycarp wants for each starting city i to find out how close he can get to the capital. More formally: he wants to find the minimal value of d_j that Polycarp can get from the city i to the city j according to the rules described above.
Input
The first line contains one integer t (1 β€ t β€ 10^4) β the number of test cases. Then t test cases follow.
Each test case is preceded by an empty line.
The first line of each test case contains two integers n (2 β€ n β€ 2 β
10^5) and m (1 β€ m β€ 2 β
10^5) β number of cities and roads, respectively.
This is followed by m lines describing the roads. Each road is characterized by two integers u and v (1 β€ u, v β€ n, u β v) β the numbers of cities connected by a one-way road.
It is guaranteed that the sums of n and m over all test cases do not exceed 2 β
10^5.
It is guaranteed that for each pair of different cities (u, v) there is at most one road from u to v (but a pair of roads from u to v and from v to u β is valid).
It is guaranteed that there is a path from the capital to all cities.
Output
For each test case, on a separate line output n numbers, the i-th of which is equal to the minimum possible distance from the capital to the city where Polycarp ended his journey.
Example
Input
3
6 7
1 2
1 3
2 5
2 4
5 1
3 6
6 2
2 2
1 2
2 1
6 8
1 2
1 5
2 6
6 1
2 3
3 4
4 2
5 4
Output
0 0 1 2 0 1
0 0
0 0 2 1 1 0
Submitted Solution:
```
for _ in range(int(input())):
input()
n, m = list(map(int,input().split()))
q = [[int(i) for i in input().split()] for j in range(m)]
tree = {i: [] for i in range(1, n+1)}
rTree = {i: [] for i in range(1, n+1)}
for i in q:
tree[i[0]].append(i[1])
rTree[i[1]].append(i[0])
weight = {i: n for i in range(1, n+1)}
weight[1] = 0
r = [1]
pas = set()
while r!= []:
i = r.pop()
if i not in pas:
pas.add(i)
for j in tree[i]:
r.append(j)
weight[j] = min(weight[j], weight[i]+1)
print(tree)
tree = weight.copy()
print(tree)
r = [1]
t= 1
pas = set()
while r!= []:
i = r.pop()
if i not in pas:
pas.add(i)
for j in rTree[i]:
if j!= 1:
r.append(j)
if tree[j]> tree[i]:
if t == 1:
weight[j] = weight[i]
else:
weight[j] = tree[i]
elif t == 1:
weight[j] = weight[i]
t-= 1
for i in range(1,n+1):
print(weight[i], end = " ")
print()
```
No
| 90,360 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
There are n cities in Berland. The city numbered 1 is the capital. Some pairs of cities are connected by a one-way road of length 1.
Before the trip, Polycarp for each city found out the value of d_i β the shortest distance from the capital (the 1-st city) to the i-th city.
Polycarp begins his journey in the city with number s and, being in the i-th city, chooses one of the following actions:
1. Travel from the i-th city to the j-th city if there is a road from the i-th city to the j-th and d_i < d_j;
2. Travel from the i-th city to the j-th city if there is a road from the i-th city to the j-th and d_i β₯ d_j;
3. Stop traveling.
Since the government of Berland does not want all people to come to the capital, so Polycarp no more than once can take the second action from the list. in other words, he can perform the second action 0 or 1 time during his journey. Polycarp, on the other hand, wants to be as close to the capital as possible.
<image>
For example, if n = 6 and the cities are connected, as in the picture above, then Polycarp could have made the following travels (not all possible options):
* 2 β 5 β 1 β 2 β 5;
* 3 β 6 β 2;
* 1 β 3 β 6 β 2 β 5.
Polycarp wants for each starting city i to find out how close he can get to the capital. More formally: he wants to find the minimal value of d_j that Polycarp can get from the city i to the city j according to the rules described above.
Input
The first line contains one integer t (1 β€ t β€ 10^4) β the number of test cases. Then t test cases follow.
Each test case is preceded by an empty line.
The first line of each test case contains two integers n (2 β€ n β€ 2 β
10^5) and m (1 β€ m β€ 2 β
10^5) β number of cities and roads, respectively.
This is followed by m lines describing the roads. Each road is characterized by two integers u and v (1 β€ u, v β€ n, u β v) β the numbers of cities connected by a one-way road.
It is guaranteed that the sums of n and m over all test cases do not exceed 2 β
10^5.
It is guaranteed that for each pair of different cities (u, v) there is at most one road from u to v (but a pair of roads from u to v and from v to u β is valid).
It is guaranteed that there is a path from the capital to all cities.
Output
For each test case, on a separate line output n numbers, the i-th of which is equal to the minimum possible distance from the capital to the city where Polycarp ended his journey.
Example
Input
3
6 7
1 2
1 3
2 5
2 4
5 1
3 6
6 2
2 2
1 2
2 1
6 8
1 2
1 5
2 6
6 1
2 3
3 4
4 2
5 4
Output
0 0 1 2 0 1
0 0
0 0 2 1 1 0
Submitted Solution:
```
from collections import defaultdict as dd,deque as dq
import sys
import bisect
input=sys.stdin.readline
t=int(input())
inf=10**6
def bfs(dis,d,n):
vis=[0]*(n+1)
q=dq([1])
dis[1]=0
while q:
u=q.pop()
val=dis[u]
for i in d[u]:
if(dis[i]>val+1):
dis[i]=val+1
q.append(i)
while t:
d=dd(list)
rd=dd(list)
_=input().split()
n,m=map(int,input().split())
dis=[inf]*(n+1)
dis1=[inf]*(n+1)
for i in range(m):
u,v=map(int,input().split())
d[u].append(v)
rd[v].append(u)
bfs(dis,d,n)
bfs(dis1,rd,n)
res=[0]*(n+1)
#print(*dis)
#print(*dis1)
for i in range(1,n+1):
res[i]=dis[i]
for j in d[i]:
#print(i,j)
if(dis1[j]-1<dis[j] and dis[j]>dis[i]):
res[i]=dis1[j]-1
res[i]=min(res[i],dis[j])
res[i]=max(res[i],0)
print(res[i],end=" ")
print()
t-=1
```
No
| 90,361 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
There are n cities in Berland. The city numbered 1 is the capital. Some pairs of cities are connected by a one-way road of length 1.
Before the trip, Polycarp for each city found out the value of d_i β the shortest distance from the capital (the 1-st city) to the i-th city.
Polycarp begins his journey in the city with number s and, being in the i-th city, chooses one of the following actions:
1. Travel from the i-th city to the j-th city if there is a road from the i-th city to the j-th and d_i < d_j;
2. Travel from the i-th city to the j-th city if there is a road from the i-th city to the j-th and d_i β₯ d_j;
3. Stop traveling.
Since the government of Berland does not want all people to come to the capital, so Polycarp no more than once can take the second action from the list. in other words, he can perform the second action 0 or 1 time during his journey. Polycarp, on the other hand, wants to be as close to the capital as possible.
<image>
For example, if n = 6 and the cities are connected, as in the picture above, then Polycarp could have made the following travels (not all possible options):
* 2 β 5 β 1 β 2 β 5;
* 3 β 6 β 2;
* 1 β 3 β 6 β 2 β 5.
Polycarp wants for each starting city i to find out how close he can get to the capital. More formally: he wants to find the minimal value of d_j that Polycarp can get from the city i to the city j according to the rules described above.
Input
The first line contains one integer t (1 β€ t β€ 10^4) β the number of test cases. Then t test cases follow.
Each test case is preceded by an empty line.
The first line of each test case contains two integers n (2 β€ n β€ 2 β
10^5) and m (1 β€ m β€ 2 β
10^5) β number of cities and roads, respectively.
This is followed by m lines describing the roads. Each road is characterized by two integers u and v (1 β€ u, v β€ n, u β v) β the numbers of cities connected by a one-way road.
It is guaranteed that the sums of n and m over all test cases do not exceed 2 β
10^5.
It is guaranteed that for each pair of different cities (u, v) there is at most one road from u to v (but a pair of roads from u to v and from v to u β is valid).
It is guaranteed that there is a path from the capital to all cities.
Output
For each test case, on a separate line output n numbers, the i-th of which is equal to the minimum possible distance from the capital to the city where Polycarp ended his journey.
Example
Input
3
6 7
1 2
1 3
2 5
2 4
5 1
3 6
6 2
2 2
1 2
2 1
6 8
1 2
1 5
2 6
6 1
2 3
3 4
4 2
5 4
Output
0 0 1 2 0 1
0 0
0 0 2 1 1 0
Submitted Solution:
```
import sys
from collections import deque as dq
input = sys.stdin.readline
for _ in range(int(input())):
input()
n, m = map(int, input().split())
e = [[] for _ in range(n + 1)]
re = [[] for _ in range(n + 1)]
for _ in range(m):
u, v = map(int, input().split())
e[u].append(v)
re[v].append(u)
Q = dq([1])
d = [n] * (n + 1)
d[1] = 0
while len(Q):
x = Q.popleft()
for y in e[x]:
if d[y] > d[x] + 1:
d[y] = d[x] + 1
Q.append(y)
dp = [d[: ] for _ in range(2)]
vis = [0] * (n + 1)
s = [x for _, x in sorted([(d[i], i) for i in range(n)], reverse = True)]
#print(s)
while len(s):
x = s.pop()
for y in re[x]:
if vis[y]: continue
if d[y] >= d[x] and dp[1][y] > dp[0][x]:
dp[1][y] = dp[0][x]
s.append(y)
vis[y] = 1
if d[y] < d[x]:
if dp[1][y] > dp[1][x]: dp[1][y] = dp[1][x]
if dp[0][y] > dp[0][x]: dp[0][y] = dp[0][x]
s.append(y)
vis[y] = 1
#print(s, dp, x)
res = [min(dp[0][i], dp[1][i]) for i in range(1, n + 1)]
print(*res)
```
No
| 90,362 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
There are n cities in Berland. The city numbered 1 is the capital. Some pairs of cities are connected by a one-way road of length 1.
Before the trip, Polycarp for each city found out the value of d_i β the shortest distance from the capital (the 1-st city) to the i-th city.
Polycarp begins his journey in the city with number s and, being in the i-th city, chooses one of the following actions:
1. Travel from the i-th city to the j-th city if there is a road from the i-th city to the j-th and d_i < d_j;
2. Travel from the i-th city to the j-th city if there is a road from the i-th city to the j-th and d_i β₯ d_j;
3. Stop traveling.
Since the government of Berland does not want all people to come to the capital, so Polycarp no more than once can take the second action from the list. in other words, he can perform the second action 0 or 1 time during his journey. Polycarp, on the other hand, wants to be as close to the capital as possible.
<image>
For example, if n = 6 and the cities are connected, as in the picture above, then Polycarp could have made the following travels (not all possible options):
* 2 β 5 β 1 β 2 β 5;
* 3 β 6 β 2;
* 1 β 3 β 6 β 2 β 5.
Polycarp wants for each starting city i to find out how close he can get to the capital. More formally: he wants to find the minimal value of d_j that Polycarp can get from the city i to the city j according to the rules described above.
Input
The first line contains one integer t (1 β€ t β€ 10^4) β the number of test cases. Then t test cases follow.
Each test case is preceded by an empty line.
The first line of each test case contains two integers n (2 β€ n β€ 2 β
10^5) and m (1 β€ m β€ 2 β
10^5) β number of cities and roads, respectively.
This is followed by m lines describing the roads. Each road is characterized by two integers u and v (1 β€ u, v β€ n, u β v) β the numbers of cities connected by a one-way road.
It is guaranteed that the sums of n and m over all test cases do not exceed 2 β
10^5.
It is guaranteed that for each pair of different cities (u, v) there is at most one road from u to v (but a pair of roads from u to v and from v to u β is valid).
It is guaranteed that there is a path from the capital to all cities.
Output
For each test case, on a separate line output n numbers, the i-th of which is equal to the minimum possible distance from the capital to the city where Polycarp ended his journey.
Example
Input
3
6 7
1 2
1 3
2 5
2 4
5 1
3 6
6 2
2 2
1 2
2 1
6 8
1 2
1 5
2 6
6 1
2 3
3 4
4 2
5 4
Output
0 0 1 2 0 1
0 0
0 0 2 1 1 0
Submitted Solution:
```
import sys
input = sys.stdin.readline
from collections import *
def bfs():
q = deque([0])
dist = [-1]*n
dist[0] = 0
while q:
v = q.popleft()
for nv in G[v]:
if dist[nv]==-1:
dist[nv] = dist[v]+1
q.append(nv)
return dist
for _ in range(int(input())):
input()
n, m = map(int, input().split())
G = [[] for _ in range(n)]
edges = []
for _ in range(m):
u, v = map(int, input().split())
G[u-1].append(v-1)
edges.append((u-1, v-1))
dist = bfs()
m = [dist[v] for v in range(n)]
for v in range(n):
for nv in G[v]:
m[v] = min(m[v], dist[nv])
ins = [0]*n
outs = defaultdict(list)
for u, v in edges:
if dist[u]<dist[v]:
ins[v] += 1
outs[u].append(v)
q = deque([v for v in range(n)])
order = []
while q:
v = q.popleft()
order.append(v)
for nv in outs[v]:
ins[nv] -= 1
if ins[nv]==0:
q.append(nv)
for v in order[::-1]:
for nv in outs[v]:
m[v] = min(m[v], m[nv])
print(*m)
```
No
| 90,363 |
Provide tags and a correct Python 3 solution for this coding contest problem.
You are given a string s, consisting only of characters '0' or '1'. Let |s| be the length of s.
You are asked to choose some integer k (k > 0) and find a sequence a of length k such that:
* 1 β€ a_1 < a_2 < ... < a_k β€ |s|;
* a_{i-1} + 1 < a_i for all i from 2 to k.
The characters at positions a_1, a_2, ..., a_k are removed, the remaining characters are concatenated without changing the order. So, in other words, the positions in the sequence a should not be adjacent.
Let the resulting string be s'. s' is called sorted if for all i from 2 to |s'| s'_{i-1} β€ s'_i.
Does there exist such a sequence a that the resulting string s' is sorted?
Input
The first line contains a single integer t (1 β€ t β€ 1000) β the number of testcases.
Then the descriptions of t testcases follow.
The only line of each testcase contains a string s (2 β€ |s| β€ 100). Each character is either '0' or '1'.
Output
For each testcase print "YES" if there exists a sequence a such that removing the characters at positions a_1, a_2, ..., a_k and concatenating the parts without changing the order produces a sorted string.
Otherwise, print "NO".
You may print every letter in any case you want (so, for example, the strings yEs, yes, Yes and YES are all recognized as positive answer).
Example
Input
5
10101011011
0000
11111
110
1100
Output
YES
YES
YES
YES
NO
Note
In the first testcase you can choose a sequence a=[1,3,6,9]. Removing the underlined letters from "10101011011" will produce a string "0011111", which is sorted.
In the second and the third testcases the sequences are already sorted.
In the fourth testcase you can choose a sequence a=[3]. s'= "11", which is sorted.
In the fifth testcase there is no way to choose a sequence a such that s' is sorted.
Tags: brute force, dp, greedy, implementation
Correct Solution:
```
t=int(input())
for _ in range(t):
s=input()
n=len(s)
a,b=-1,-1
if s.count('1')==n or s.count('0')==n:
print("YES")
else:
a=s.find("11")
b=s.rfind("00")
if a==-1 or b==-1:
print("YES")
else:
if a<b:
print("NO")
else:
print("YES")
```
| 90,364 |
Provide tags and a correct Python 3 solution for this coding contest problem.
You are given a string s, consisting only of characters '0' or '1'. Let |s| be the length of s.
You are asked to choose some integer k (k > 0) and find a sequence a of length k such that:
* 1 β€ a_1 < a_2 < ... < a_k β€ |s|;
* a_{i-1} + 1 < a_i for all i from 2 to k.
The characters at positions a_1, a_2, ..., a_k are removed, the remaining characters are concatenated without changing the order. So, in other words, the positions in the sequence a should not be adjacent.
Let the resulting string be s'. s' is called sorted if for all i from 2 to |s'| s'_{i-1} β€ s'_i.
Does there exist such a sequence a that the resulting string s' is sorted?
Input
The first line contains a single integer t (1 β€ t β€ 1000) β the number of testcases.
Then the descriptions of t testcases follow.
The only line of each testcase contains a string s (2 β€ |s| β€ 100). Each character is either '0' or '1'.
Output
For each testcase print "YES" if there exists a sequence a such that removing the characters at positions a_1, a_2, ..., a_k and concatenating the parts without changing the order produces a sorted string.
Otherwise, print "NO".
You may print every letter in any case you want (so, for example, the strings yEs, yes, Yes and YES are all recognized as positive answer).
Example
Input
5
10101011011
0000
11111
110
1100
Output
YES
YES
YES
YES
NO
Note
In the first testcase you can choose a sequence a=[1,3,6,9]. Removing the underlined letters from "10101011011" will produce a string "0011111", which is sorted.
In the second and the third testcases the sequences are already sorted.
In the fourth testcase you can choose a sequence a=[3]. s'= "11", which is sorted.
In the fifth testcase there is no way to choose a sequence a such that s' is sorted.
Tags: brute force, dp, greedy, implementation
Correct Solution:
```
tc = int(input())
for t in range(tc):
seq = input()
rmost00 = seq.rfind("00")
lmost11 = seq.find("11")
if rmost00 >= 0 and lmost11 >= 0 and rmost00 > lmost11:
print("NO")
else:
print("YES")
# prev = seq[0]
# for i in range(1, len(seq)):
# item = seq[i]
# if item <
```
| 90,365 |
Provide tags and a correct Python 3 solution for this coding contest problem.
You are given a string s, consisting only of characters '0' or '1'. Let |s| be the length of s.
You are asked to choose some integer k (k > 0) and find a sequence a of length k such that:
* 1 β€ a_1 < a_2 < ... < a_k β€ |s|;
* a_{i-1} + 1 < a_i for all i from 2 to k.
The characters at positions a_1, a_2, ..., a_k are removed, the remaining characters are concatenated without changing the order. So, in other words, the positions in the sequence a should not be adjacent.
Let the resulting string be s'. s' is called sorted if for all i from 2 to |s'| s'_{i-1} β€ s'_i.
Does there exist such a sequence a that the resulting string s' is sorted?
Input
The first line contains a single integer t (1 β€ t β€ 1000) β the number of testcases.
Then the descriptions of t testcases follow.
The only line of each testcase contains a string s (2 β€ |s| β€ 100). Each character is either '0' or '1'.
Output
For each testcase print "YES" if there exists a sequence a such that removing the characters at positions a_1, a_2, ..., a_k and concatenating the parts without changing the order produces a sorted string.
Otherwise, print "NO".
You may print every letter in any case you want (so, for example, the strings yEs, yes, Yes and YES are all recognized as positive answer).
Example
Input
5
10101011011
0000
11111
110
1100
Output
YES
YES
YES
YES
NO
Note
In the first testcase you can choose a sequence a=[1,3,6,9]. Removing the underlined letters from "10101011011" will produce a string "0011111", which is sorted.
In the second and the third testcases the sequences are already sorted.
In the fourth testcase you can choose a sequence a=[3]. s'= "11", which is sorted.
In the fifth testcase there is no way to choose a sequence a such that s' is sorted.
Tags: brute force, dp, greedy, implementation
Correct Solution:
```
#!/usr/bin/env python
from __future__ import division, print_function
import os
import sys
sys.setrecursionlimit(1000000)
from io import BytesIO, IOBase
if sys.version_info[0] < 3:
from __builtin__ import xrange as range
from future_builtins import ascii, filter, hex, map, oct, zip
def main():
pass
# 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")
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)
input = lambda: sys.stdin.readline().rstrip("\r\n")
'''
b = list(map(int, input().split()))
arr.sort(key=lambda x :x[0]-x[1])
'''
import math
import sys
import bisect
from collections import defaultdict
for t in range(int(input())):
# n, k1, k2 = map(int, input().split())
s = input()
flag = True
idx = -1
idx0 = -1
for i in range(len(s)-1):
if s[i] == '1' and s[i+1] == '1' and flag:
idx = i
flag = False
if s[i] == '0' and s[i+1] == '0':
idx0 = i
if idx == -1 or idx0 == -1:
print("YES")
continue
if idx < idx0:
print("NO")
else:
print("YES")
if __name__ == "__main__":
main()
```
| 90,366 |
Provide tags and a correct Python 3 solution for this coding contest problem.
You are given a string s, consisting only of characters '0' or '1'. Let |s| be the length of s.
You are asked to choose some integer k (k > 0) and find a sequence a of length k such that:
* 1 β€ a_1 < a_2 < ... < a_k β€ |s|;
* a_{i-1} + 1 < a_i for all i from 2 to k.
The characters at positions a_1, a_2, ..., a_k are removed, the remaining characters are concatenated without changing the order. So, in other words, the positions in the sequence a should not be adjacent.
Let the resulting string be s'. s' is called sorted if for all i from 2 to |s'| s'_{i-1} β€ s'_i.
Does there exist such a sequence a that the resulting string s' is sorted?
Input
The first line contains a single integer t (1 β€ t β€ 1000) β the number of testcases.
Then the descriptions of t testcases follow.
The only line of each testcase contains a string s (2 β€ |s| β€ 100). Each character is either '0' or '1'.
Output
For each testcase print "YES" if there exists a sequence a such that removing the characters at positions a_1, a_2, ..., a_k and concatenating the parts without changing the order produces a sorted string.
Otherwise, print "NO".
You may print every letter in any case you want (so, for example, the strings yEs, yes, Yes and YES are all recognized as positive answer).
Example
Input
5
10101011011
0000
11111
110
1100
Output
YES
YES
YES
YES
NO
Note
In the first testcase you can choose a sequence a=[1,3,6,9]. Removing the underlined letters from "10101011011" will produce a string "0011111", which is sorted.
In the second and the third testcases the sequences are already sorted.
In the fourth testcase you can choose a sequence a=[3]. s'= "11", which is sorted.
In the fifth testcase there is no way to choose a sequence a such that s' is sorted.
Tags: brute force, dp, greedy, implementation
Correct Solution:
```
t = int(input())
results = []
def find_dob(s):
return [(i, s[i]) for i in range(len(s)-1) if not(s[i]^s[i+1])]
for i in range(t):
s = input()
s = [int(c) for c in s]
dobs = find_dob(s)
dobs_z = [a for (a, b) in dobs if b==0]
dobs_o = [a for (a, b) in dobs if b==1]
if (len(dobs_z)==0) or len(dobs_o)==0:
results.append('yes')
else:
if dobs_z[-1]<dobs_o[0]:
results.append('yes')
else:
results.append('no')
for i in range(t):
print(results.pop(0))
```
| 90,367 |
Provide tags and a correct Python 3 solution for this coding contest problem.
You are given a string s, consisting only of characters '0' or '1'. Let |s| be the length of s.
You are asked to choose some integer k (k > 0) and find a sequence a of length k such that:
* 1 β€ a_1 < a_2 < ... < a_k β€ |s|;
* a_{i-1} + 1 < a_i for all i from 2 to k.
The characters at positions a_1, a_2, ..., a_k are removed, the remaining characters are concatenated without changing the order. So, in other words, the positions in the sequence a should not be adjacent.
Let the resulting string be s'. s' is called sorted if for all i from 2 to |s'| s'_{i-1} β€ s'_i.
Does there exist such a sequence a that the resulting string s' is sorted?
Input
The first line contains a single integer t (1 β€ t β€ 1000) β the number of testcases.
Then the descriptions of t testcases follow.
The only line of each testcase contains a string s (2 β€ |s| β€ 100). Each character is either '0' or '1'.
Output
For each testcase print "YES" if there exists a sequence a such that removing the characters at positions a_1, a_2, ..., a_k and concatenating the parts without changing the order produces a sorted string.
Otherwise, print "NO".
You may print every letter in any case you want (so, for example, the strings yEs, yes, Yes and YES are all recognized as positive answer).
Example
Input
5
10101011011
0000
11111
110
1100
Output
YES
YES
YES
YES
NO
Note
In the first testcase you can choose a sequence a=[1,3,6,9]. Removing the underlined letters from "10101011011" will produce a string "0011111", which is sorted.
In the second and the third testcases the sequences are already sorted.
In the fourth testcase you can choose a sequence a=[3]. s'= "11", which is sorted.
In the fifth testcase there is no way to choose a sequence a such that s' is sorted.
Tags: brute force, dp, greedy, implementation
Correct Solution:
```
for _ in range(int(input())):
s=input()
n=len(s)
f=True
o,z = s.count('1'),s.count('0')
if o==n or z==n:
print('YES')
continue
for i in range(n-1):
if s[i]=='1' and s[i+1]=='1':
for i in range(i+2,n-1):
if s[i]=='0' and s[i+1]=='0':
f=False
if f:
print('YES')
else:
print('NO')
```
| 90,368 |
Provide tags and a correct Python 3 solution for this coding contest problem.
You are given a string s, consisting only of characters '0' or '1'. Let |s| be the length of s.
You are asked to choose some integer k (k > 0) and find a sequence a of length k such that:
* 1 β€ a_1 < a_2 < ... < a_k β€ |s|;
* a_{i-1} + 1 < a_i for all i from 2 to k.
The characters at positions a_1, a_2, ..., a_k are removed, the remaining characters are concatenated without changing the order. So, in other words, the positions in the sequence a should not be adjacent.
Let the resulting string be s'. s' is called sorted if for all i from 2 to |s'| s'_{i-1} β€ s'_i.
Does there exist such a sequence a that the resulting string s' is sorted?
Input
The first line contains a single integer t (1 β€ t β€ 1000) β the number of testcases.
Then the descriptions of t testcases follow.
The only line of each testcase contains a string s (2 β€ |s| β€ 100). Each character is either '0' or '1'.
Output
For each testcase print "YES" if there exists a sequence a such that removing the characters at positions a_1, a_2, ..., a_k and concatenating the parts without changing the order produces a sorted string.
Otherwise, print "NO".
You may print every letter in any case you want (so, for example, the strings yEs, yes, Yes and YES are all recognized as positive answer).
Example
Input
5
10101011011
0000
11111
110
1100
Output
YES
YES
YES
YES
NO
Note
In the first testcase you can choose a sequence a=[1,3,6,9]. Removing the underlined letters from "10101011011" will produce a string "0011111", which is sorted.
In the second and the third testcases the sequences are already sorted.
In the fourth testcase you can choose a sequence a=[3]. s'= "11", which is sorted.
In the fifth testcase there is no way to choose a sequence a such that s' is sorted.
Tags: brute force, dp, greedy, implementation
Correct Solution:
```
import sys
import math
import bisect
import functools
from functools import lru_cache
from sys import stdin, stdout
from math import gcd, floor, sqrt, log, ceil
from heapq import heappush, heappop, heapify
from collections import defaultdict as dd
from collections import Counter as cc
from bisect import bisect_left as bl
from bisect import bisect_right as br
def lcm(a, b):
return abs(a*b) // math.gcd(a, b)
'''
testcase = sys.argv[1]
f = open(testcase, "r")
input = f.readline
'''
sys.setrecursionlimit(100000000)
intinp = lambda: int(input().strip())
stripinp = lambda: input().strip()
fltarr = lambda: list(map(float,input().strip().split()))
intarr = lambda: list(map(int,input().strip().split()))
ceildiv = lambda x,d: x//d if(x%d==0) else x//d+1
MOD=1_000_000_007
@lru_cache(None)
def help(need, left):
if left == "":
#print(sorted(curr), curr, s)
return True
if len(left) > 1:
if left[0] == "0" and need and left[1] == "1":
return help(need, left[2:])
elif left[1] == "0" and need and left[0] == "1":
return help(need, left[1:])
elif need and left[1] == "0" and left[0] == "0":
return False
else:
return help(need or int(left[1]), left[2:]) or help(need or int(left[0]), left[1:])
else:
if left[0] == "0" and need:
return help(need, left[1:])
else:
return help(need or int(left[0]), left[1:]) or help(need, left[1:])
num_cases = intinp()
#num_cases = 1
for _ in range(num_cases):
#n, k = intarr()
#n = intinp()
s = stripinp()
#arr = intarr()
if help(0, s):
print("YES")
else:
print("NO")
```
| 90,369 |
Provide tags and a correct Python 3 solution for this coding contest problem.
You are given a string s, consisting only of characters '0' or '1'. Let |s| be the length of s.
You are asked to choose some integer k (k > 0) and find a sequence a of length k such that:
* 1 β€ a_1 < a_2 < ... < a_k β€ |s|;
* a_{i-1} + 1 < a_i for all i from 2 to k.
The characters at positions a_1, a_2, ..., a_k are removed, the remaining characters are concatenated without changing the order. So, in other words, the positions in the sequence a should not be adjacent.
Let the resulting string be s'. s' is called sorted if for all i from 2 to |s'| s'_{i-1} β€ s'_i.
Does there exist such a sequence a that the resulting string s' is sorted?
Input
The first line contains a single integer t (1 β€ t β€ 1000) β the number of testcases.
Then the descriptions of t testcases follow.
The only line of each testcase contains a string s (2 β€ |s| β€ 100). Each character is either '0' or '1'.
Output
For each testcase print "YES" if there exists a sequence a such that removing the characters at positions a_1, a_2, ..., a_k and concatenating the parts without changing the order produces a sorted string.
Otherwise, print "NO".
You may print every letter in any case you want (so, for example, the strings yEs, yes, Yes and YES are all recognized as positive answer).
Example
Input
5
10101011011
0000
11111
110
1100
Output
YES
YES
YES
YES
NO
Note
In the first testcase you can choose a sequence a=[1,3,6,9]. Removing the underlined letters from "10101011011" will produce a string "0011111", which is sorted.
In the second and the third testcases the sequences are already sorted.
In the fourth testcase you can choose a sequence a=[3]. s'= "11", which is sorted.
In the fifth testcase there is no way to choose a sequence a such that s' is sorted.
Tags: brute force, dp, greedy, implementation
Correct Solution:
```
import sys
def solve(s):
n = len(s)
ans = False
for i in range(n):
local_ans = True
removal = []
for j in range(i):
if s[j] == "1":
removal.append(j)
for j in range(i, n):
if s[j] == "0":
removal.append(j)
for i in range(1, len(removal)):
if removal[i-1] + 1 >= removal[i]:
local_ans = False
ans |= local_ans
return 'YES' if ans else 'NO'
if 1 == 2:
sys.stdin = open('input.txt', 'r')
sys.stdout = open('output.txt', 'w')
else:
input = sys.stdin.readline
T = int(input())
for _ in range(T):
s = input()
print(solve(s))
```
| 90,370 |
Provide tags and a correct Python 3 solution for this coding contest problem.
You are given a string s, consisting only of characters '0' or '1'. Let |s| be the length of s.
You are asked to choose some integer k (k > 0) and find a sequence a of length k such that:
* 1 β€ a_1 < a_2 < ... < a_k β€ |s|;
* a_{i-1} + 1 < a_i for all i from 2 to k.
The characters at positions a_1, a_2, ..., a_k are removed, the remaining characters are concatenated without changing the order. So, in other words, the positions in the sequence a should not be adjacent.
Let the resulting string be s'. s' is called sorted if for all i from 2 to |s'| s'_{i-1} β€ s'_i.
Does there exist such a sequence a that the resulting string s' is sorted?
Input
The first line contains a single integer t (1 β€ t β€ 1000) β the number of testcases.
Then the descriptions of t testcases follow.
The only line of each testcase contains a string s (2 β€ |s| β€ 100). Each character is either '0' or '1'.
Output
For each testcase print "YES" if there exists a sequence a such that removing the characters at positions a_1, a_2, ..., a_k and concatenating the parts without changing the order produces a sorted string.
Otherwise, print "NO".
You may print every letter in any case you want (so, for example, the strings yEs, yes, Yes and YES are all recognized as positive answer).
Example
Input
5
10101011011
0000
11111
110
1100
Output
YES
YES
YES
YES
NO
Note
In the first testcase you can choose a sequence a=[1,3,6,9]. Removing the underlined letters from "10101011011" will produce a string "0011111", which is sorted.
In the second and the third testcases the sequences are already sorted.
In the fourth testcase you can choose a sequence a=[3]. s'= "11", which is sorted.
In the fifth testcase there is no way to choose a sequence a such that s' is sorted.
Tags: brute force, dp, greedy, implementation
Correct Solution:
```
import sys
input = sys.stdin.readline
for _ in range(int(input())):
s = input()
try:
i = s.index('11') + 2
if '00' in s[i:]:
print("NO")
else:
print("YES")
except:
print("YES")
```
| 90,371 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
You are given a string s, consisting only of characters '0' or '1'. Let |s| be the length of s.
You are asked to choose some integer k (k > 0) and find a sequence a of length k such that:
* 1 β€ a_1 < a_2 < ... < a_k β€ |s|;
* a_{i-1} + 1 < a_i for all i from 2 to k.
The characters at positions a_1, a_2, ..., a_k are removed, the remaining characters are concatenated without changing the order. So, in other words, the positions in the sequence a should not be adjacent.
Let the resulting string be s'. s' is called sorted if for all i from 2 to |s'| s'_{i-1} β€ s'_i.
Does there exist such a sequence a that the resulting string s' is sorted?
Input
The first line contains a single integer t (1 β€ t β€ 1000) β the number of testcases.
Then the descriptions of t testcases follow.
The only line of each testcase contains a string s (2 β€ |s| β€ 100). Each character is either '0' or '1'.
Output
For each testcase print "YES" if there exists a sequence a such that removing the characters at positions a_1, a_2, ..., a_k and concatenating the parts without changing the order produces a sorted string.
Otherwise, print "NO".
You may print every letter in any case you want (so, for example, the strings yEs, yes, Yes and YES are all recognized as positive answer).
Example
Input
5
10101011011
0000
11111
110
1100
Output
YES
YES
YES
YES
NO
Note
In the first testcase you can choose a sequence a=[1,3,6,9]. Removing the underlined letters from "10101011011" will produce a string "0011111", which is sorted.
In the second and the third testcases the sequences are already sorted.
In the fourth testcase you can choose a sequence a=[3]. s'= "11", which is sorted.
In the fifth testcase there is no way to choose a sequence a such that s' is sorted.
Submitted Solution:
```
t= int(input())
for p in range(t):
n= input()
if n.find("11") == -1 or n.find("00")== -1:
print("YES")
else:
if n.find("00", n.find("11")+ 1) == -1:
print("YES")
else:
print("NO")
```
Yes
| 90,372 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
You are given a string s, consisting only of characters '0' or '1'. Let |s| be the length of s.
You are asked to choose some integer k (k > 0) and find a sequence a of length k such that:
* 1 β€ a_1 < a_2 < ... < a_k β€ |s|;
* a_{i-1} + 1 < a_i for all i from 2 to k.
The characters at positions a_1, a_2, ..., a_k are removed, the remaining characters are concatenated without changing the order. So, in other words, the positions in the sequence a should not be adjacent.
Let the resulting string be s'. s' is called sorted if for all i from 2 to |s'| s'_{i-1} β€ s'_i.
Does there exist such a sequence a that the resulting string s' is sorted?
Input
The first line contains a single integer t (1 β€ t β€ 1000) β the number of testcases.
Then the descriptions of t testcases follow.
The only line of each testcase contains a string s (2 β€ |s| β€ 100). Each character is either '0' or '1'.
Output
For each testcase print "YES" if there exists a sequence a such that removing the characters at positions a_1, a_2, ..., a_k and concatenating the parts without changing the order produces a sorted string.
Otherwise, print "NO".
You may print every letter in any case you want (so, for example, the strings yEs, yes, Yes and YES are all recognized as positive answer).
Example
Input
5
10101011011
0000
11111
110
1100
Output
YES
YES
YES
YES
NO
Note
In the first testcase you can choose a sequence a=[1,3,6,9]. Removing the underlined letters from "10101011011" will produce a string "0011111", which is sorted.
In the second and the third testcases the sequences are already sorted.
In the fourth testcase you can choose a sequence a=[3]. s'= "11", which is sorted.
In the fifth testcase there is no way to choose a sequence a such that s' is sorted.
Submitted Solution:
```
import os
import sys
from io import BytesIO, IOBase
import math
BUFSIZE = 8192
from collections import Counter
class FastIO(IOBase):
newlines = 0
def __init__(self, file):
self._fd = file.fileno()
self.buffer = BytesIO()
self.writable = "x" in file.mode or "r" not in file.mode
self.write = self.buffer.write if self.writable else None
def read(self):
while True:
b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
if not b:
break
ptr = self.buffer.tell()
self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr)
self.newlines = 0
return self.buffer.read()
def readline(self):
while self.newlines == 0:
b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
self.newlines = b.count(b"\n") + (not b)
ptr = self.buffer.tell()
self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr)
self.newlines -= 1
return self.buffer.readline()
def flush(self):
if self.writable:
os.write(self._fd, self.buffer.getvalue())
self.buffer.truncate(0), self.buffer.seek(0)
class IOWrapper(IOBase):
def __init__(self, file):
self.buffer = FastIO(file)
self.flush = self.buffer.flush
self.writable = self.buffer.writable
self.write = lambda s: self.buffer.write(s.encode("ascii"))
self.read = lambda: self.buffer.read().decode("ascii")
self.readline = lambda: self.buffer.readline().decode("ascii")
sys.stdin, sys.stdout = IOWrapper(sys.stdin), IOWrapper(sys.stdout)
input = lambda: sys.stdin.readline().rstrip("\r\n")
#-------------------game starts now---------------------------------------------------
# t=1
t=(int)(input())
for _ in range(t):
# n=(int)(input())
# l=list(map(int,input().split()))
# a,b=map(int,input().split())
s=input()
# p=-1
# if '1' not in s:
# p=-1
# else:
# p=s.index('1')
# if p==len(s)-1 or p==-1:
# print("YES")
# else:
# f=True
# for i in range(p+1,len(s)):
# if s[i]==s[i-1]=='0':
# f=False
# break
# if f:
# print("YES")
# else:
# print("NO")
f=0
for i in range (len(s)):
r=1
for j in range (1,i):
if s[j]==s[j-1]=='1':
r=0
break
for j in range (i+2,len(s)):
if s[j]==s[j-1]=='0':
r=0
break
if r==1:
f=1
break
if f:
print("YES")
else:
print("NO")
```
Yes
| 90,373 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
You are given a string s, consisting only of characters '0' or '1'. Let |s| be the length of s.
You are asked to choose some integer k (k > 0) and find a sequence a of length k such that:
* 1 β€ a_1 < a_2 < ... < a_k β€ |s|;
* a_{i-1} + 1 < a_i for all i from 2 to k.
The characters at positions a_1, a_2, ..., a_k are removed, the remaining characters are concatenated without changing the order. So, in other words, the positions in the sequence a should not be adjacent.
Let the resulting string be s'. s' is called sorted if for all i from 2 to |s'| s'_{i-1} β€ s'_i.
Does there exist such a sequence a that the resulting string s' is sorted?
Input
The first line contains a single integer t (1 β€ t β€ 1000) β the number of testcases.
Then the descriptions of t testcases follow.
The only line of each testcase contains a string s (2 β€ |s| β€ 100). Each character is either '0' or '1'.
Output
For each testcase print "YES" if there exists a sequence a such that removing the characters at positions a_1, a_2, ..., a_k and concatenating the parts without changing the order produces a sorted string.
Otherwise, print "NO".
You may print every letter in any case you want (so, for example, the strings yEs, yes, Yes and YES are all recognized as positive answer).
Example
Input
5
10101011011
0000
11111
110
1100
Output
YES
YES
YES
YES
NO
Note
In the first testcase you can choose a sequence a=[1,3,6,9]. Removing the underlined letters from "10101011011" will produce a string "0011111", which is sorted.
In the second and the third testcases the sequences are already sorted.
In the fourth testcase you can choose a sequence a=[3]. s'= "11", which is sorted.
In the fifth testcase there is no way to choose a sequence a such that s' is sorted.
Submitted Solution:
```
import sys
lines = sys.stdin.readlines()
T = int(lines[0].strip())
for t in range(T):
s = lines[t+1].strip()
L = len(s)
satisfy = True
pairOne = False
ind = -1
pairZero = False
for i in range(1, L):
if s[i] == '1' and s[i-1] == '1':
pairOne = True
ind = i
break
if pairOne:
for i in range(ind+2, L):
if s[i] == '0' and s[i-1] == '0':
pairZero = True
break
if pairZero:
print("NO")
else:
print("YES")
```
Yes
| 90,374 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
You are given a string s, consisting only of characters '0' or '1'. Let |s| be the length of s.
You are asked to choose some integer k (k > 0) and find a sequence a of length k such that:
* 1 β€ a_1 < a_2 < ... < a_k β€ |s|;
* a_{i-1} + 1 < a_i for all i from 2 to k.
The characters at positions a_1, a_2, ..., a_k are removed, the remaining characters are concatenated without changing the order. So, in other words, the positions in the sequence a should not be adjacent.
Let the resulting string be s'. s' is called sorted if for all i from 2 to |s'| s'_{i-1} β€ s'_i.
Does there exist such a sequence a that the resulting string s' is sorted?
Input
The first line contains a single integer t (1 β€ t β€ 1000) β the number of testcases.
Then the descriptions of t testcases follow.
The only line of each testcase contains a string s (2 β€ |s| β€ 100). Each character is either '0' or '1'.
Output
For each testcase print "YES" if there exists a sequence a such that removing the characters at positions a_1, a_2, ..., a_k and concatenating the parts without changing the order produces a sorted string.
Otherwise, print "NO".
You may print every letter in any case you want (so, for example, the strings yEs, yes, Yes and YES are all recognized as positive answer).
Example
Input
5
10101011011
0000
11111
110
1100
Output
YES
YES
YES
YES
NO
Note
In the first testcase you can choose a sequence a=[1,3,6,9]. Removing the underlined letters from "10101011011" will produce a string "0011111", which is sorted.
In the second and the third testcases the sequences are already sorted.
In the fourth testcase you can choose a sequence a=[3]. s'= "11", which is sorted.
In the fifth testcase there is no way to choose a sequence a such that s' is sorted.
Submitted Solution:
```
from collections import deque, defaultdict
from math import sqrt, ceil, factorial, floor, inf, log2, sqrt
import bisect
import copy
from itertools import combinations
import sys
def get_array(): return list(map(int, sys.stdin.readline().strip().split()))
def get_ints(): return map(int, sys.stdin.readline().strip().split())
def input(): return sys.stdin.readline().strip()
for _ in range(int(input())):
##n=int(input())
s=input()
flag=0
for i in range(len(s)):
ind=i
c,d=[],[]
for j in range(ind):
if s[j]=='1':
c.append(j)
for j in range(ind+1,len(s)):
if s[j]=='0':
d.append(j)
m=0
for i in range(1,len(c)):
if c[i]-c[i-1]<2:
m=1
break
for i in range(1,len(d)):
if d[i]-d[i-1]<2:
m=1
break
if m==0:
flag=1
break
if flag==0:
print("NO")
else:
print("YES")
```
Yes
| 90,375 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
You are given a string s, consisting only of characters '0' or '1'. Let |s| be the length of s.
You are asked to choose some integer k (k > 0) and find a sequence a of length k such that:
* 1 β€ a_1 < a_2 < ... < a_k β€ |s|;
* a_{i-1} + 1 < a_i for all i from 2 to k.
The characters at positions a_1, a_2, ..., a_k are removed, the remaining characters are concatenated without changing the order. So, in other words, the positions in the sequence a should not be adjacent.
Let the resulting string be s'. s' is called sorted if for all i from 2 to |s'| s'_{i-1} β€ s'_i.
Does there exist such a sequence a that the resulting string s' is sorted?
Input
The first line contains a single integer t (1 β€ t β€ 1000) β the number of testcases.
Then the descriptions of t testcases follow.
The only line of each testcase contains a string s (2 β€ |s| β€ 100). Each character is either '0' or '1'.
Output
For each testcase print "YES" if there exists a sequence a such that removing the characters at positions a_1, a_2, ..., a_k and concatenating the parts without changing the order produces a sorted string.
Otherwise, print "NO".
You may print every letter in any case you want (so, for example, the strings yEs, yes, Yes and YES are all recognized as positive answer).
Example
Input
5
10101011011
0000
11111
110
1100
Output
YES
YES
YES
YES
NO
Note
In the first testcase you can choose a sequence a=[1,3,6,9]. Removing the underlined letters from "10101011011" will produce a string "0011111", which is sorted.
In the second and the third testcases the sequences are already sorted.
In the fourth testcase you can choose a sequence a=[3]. s'= "11", which is sorted.
In the fifth testcase there is no way to choose a sequence a such that s' is sorted.
Submitted Solution:
```
import sys
from math import gcd,ceil,sqrt
INF = float('inf')
MOD = 998244353
mod = 10**9+7
from collections import Counter,defaultdict as df
from functools import reduce
def counter(l): return dict(Counter(l))
def so(x): return {k: v for k, v in sorted(x.items(), key=lambda item: item[1])}
def rev(l): return list(reversed(l))
def ini(): return int(sys.stdin.readline())
def inp(): return map(int, sys.stdin.readline().strip().split())
def li(): return list(map(int, sys.stdin.readline().strip().split()))
def input(): return sys.stdin.readline().strip()
def inputm(n,m):return [li() for i in range(m)]
for i in range(ini()):
s=input()
n=len(s)
c1=-1
c2=-1
for i in range(n-1):
if s[i]==s[i+1]:
if s[i]=='1':
c1=i
else:
c2=i
if c1==-1 or c2==-1 or c1>c2:
print('YES')
else:
print('NO')
```
No
| 90,376 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
You are given a string s, consisting only of characters '0' or '1'. Let |s| be the length of s.
You are asked to choose some integer k (k > 0) and find a sequence a of length k such that:
* 1 β€ a_1 < a_2 < ... < a_k β€ |s|;
* a_{i-1} + 1 < a_i for all i from 2 to k.
The characters at positions a_1, a_2, ..., a_k are removed, the remaining characters are concatenated without changing the order. So, in other words, the positions in the sequence a should not be adjacent.
Let the resulting string be s'. s' is called sorted if for all i from 2 to |s'| s'_{i-1} β€ s'_i.
Does there exist such a sequence a that the resulting string s' is sorted?
Input
The first line contains a single integer t (1 β€ t β€ 1000) β the number of testcases.
Then the descriptions of t testcases follow.
The only line of each testcase contains a string s (2 β€ |s| β€ 100). Each character is either '0' or '1'.
Output
For each testcase print "YES" if there exists a sequence a such that removing the characters at positions a_1, a_2, ..., a_k and concatenating the parts without changing the order produces a sorted string.
Otherwise, print "NO".
You may print every letter in any case you want (so, for example, the strings yEs, yes, Yes and YES are all recognized as positive answer).
Example
Input
5
10101011011
0000
11111
110
1100
Output
YES
YES
YES
YES
NO
Note
In the first testcase you can choose a sequence a=[1,3,6,9]. Removing the underlined letters from "10101011011" will produce a string "0011111", which is sorted.
In the second and the third testcases the sequences are already sorted.
In the fourth testcase you can choose a sequence a=[3]. s'= "11", which is sorted.
In the fifth testcase there is no way to choose a sequence a such that s' is sorted.
Submitted Solution:
```
import collections
import math
n = int(input())
for i in range(n):
s = input()
ans1 = []
ans2 = []
for i in range(len(s)):
if s[i] == "0":
ans1.append(i)
else:
ans2.append(i)
if len(ans1) <= 1 or ans1 == [i for i in range(len(s))] or len(ans2)<=1 or ans2 == [i for i in range(len(s))]:
print('YES')
else:
flag1 = 1
for i in range(1,len(ans1)):
if ans1[i] > ans1[i-1]+1:
pass
else:
flag1 = 0
flag2 = 1
for i in range(1,len(ans2)):
if ans2[i] > ans2[i-1]+1:
pass
else:
flag2 = 0
if flag1 or flag2:
print("Yes")
else:
print('nO')
```
No
| 90,377 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
You are given a string s, consisting only of characters '0' or '1'. Let |s| be the length of s.
You are asked to choose some integer k (k > 0) and find a sequence a of length k such that:
* 1 β€ a_1 < a_2 < ... < a_k β€ |s|;
* a_{i-1} + 1 < a_i for all i from 2 to k.
The characters at positions a_1, a_2, ..., a_k are removed, the remaining characters are concatenated without changing the order. So, in other words, the positions in the sequence a should not be adjacent.
Let the resulting string be s'. s' is called sorted if for all i from 2 to |s'| s'_{i-1} β€ s'_i.
Does there exist such a sequence a that the resulting string s' is sorted?
Input
The first line contains a single integer t (1 β€ t β€ 1000) β the number of testcases.
Then the descriptions of t testcases follow.
The only line of each testcase contains a string s (2 β€ |s| β€ 100). Each character is either '0' or '1'.
Output
For each testcase print "YES" if there exists a sequence a such that removing the characters at positions a_1, a_2, ..., a_k and concatenating the parts without changing the order produces a sorted string.
Otherwise, print "NO".
You may print every letter in any case you want (so, for example, the strings yEs, yes, Yes and YES are all recognized as positive answer).
Example
Input
5
10101011011
0000
11111
110
1100
Output
YES
YES
YES
YES
NO
Note
In the first testcase you can choose a sequence a=[1,3,6,9]. Removing the underlined letters from "10101011011" will produce a string "0011111", which is sorted.
In the second and the third testcases the sequences are already sorted.
In the fourth testcase you can choose a sequence a=[3]. s'= "11", which is sorted.
In the fifth testcase there is no way to choose a sequence a such that s' is sorted.
Submitted Solution:
```
t=int(input())
for i in range(t):
s=input()
l=[]
flag=0
last=0
for t in s:
l.append(int(t))
lim=len(l)
i=0
while(i<lim):
if(l[i]==1 and flag==0):
if(last+1==i):
flag=1
else:
last=i
if(l[i]==0 and flag==1):
if(last+1==i):
flag=-2
break;
else:
last=i
i+=1
if(flag==-2):
print("No");
else:
print("YES");
l.clear()
flag=0
last=0
```
No
| 90,378 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
You are given a string s, consisting only of characters '0' or '1'. Let |s| be the length of s.
You are asked to choose some integer k (k > 0) and find a sequence a of length k such that:
* 1 β€ a_1 < a_2 < ... < a_k β€ |s|;
* a_{i-1} + 1 < a_i for all i from 2 to k.
The characters at positions a_1, a_2, ..., a_k are removed, the remaining characters are concatenated without changing the order. So, in other words, the positions in the sequence a should not be adjacent.
Let the resulting string be s'. s' is called sorted if for all i from 2 to |s'| s'_{i-1} β€ s'_i.
Does there exist such a sequence a that the resulting string s' is sorted?
Input
The first line contains a single integer t (1 β€ t β€ 1000) β the number of testcases.
Then the descriptions of t testcases follow.
The only line of each testcase contains a string s (2 β€ |s| β€ 100). Each character is either '0' or '1'.
Output
For each testcase print "YES" if there exists a sequence a such that removing the characters at positions a_1, a_2, ..., a_k and concatenating the parts without changing the order produces a sorted string.
Otherwise, print "NO".
You may print every letter in any case you want (so, for example, the strings yEs, yes, Yes and YES are all recognized as positive answer).
Example
Input
5
10101011011
0000
11111
110
1100
Output
YES
YES
YES
YES
NO
Note
In the first testcase you can choose a sequence a=[1,3,6,9]. Removing the underlined letters from "10101011011" will produce a string "0011111", which is sorted.
In the second and the third testcases the sequences are already sorted.
In the fourth testcase you can choose a sequence a=[3]. s'= "11", which is sorted.
In the fifth testcase there is no way to choose a sequence a such that s' is sorted.
Submitted Solution:
```
for i in range(int(input())):
s=input()
k=list(s)
k.sort()
k="".join(k)
if k==s:
print("YES")
else:
s=s.replace("1","",1)
if "100" in s:
print("NO")
else:
print("YES")
```
No
| 90,379 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Dima overslept the alarm clock, which was supposed to raise him to school.
Dima wonders if he will have time to come to the first lesson. To do this, he needs to know the minimum time it will take him to get from home to school.
The city where Dima lives is a rectangular field of n Γ m size. Each cell (i, j) on this field is denoted by one number a_{ij}:
* The number -1 means that the passage through the cell is prohibited;
* The number 0 means that the cell is free and Dima can walk though it.
* The number x (1 β€ x β€ 10^9) means that the cell contains a portal with a cost of x. A cell with a portal is also considered free.
From any portal, Dima can go to any other portal, while the time of moving from the portal (i, j) to the portal (x, y) corresponds to the sum of their costs a_{ij} + a_{xy}.
In addition to moving between portals, Dima can also move between unoccupied cells adjacent to one side in time w. In particular, he can enter a cell with a portal and not use it.
Initially, Dima is in the upper-left cell (1, 1), and the school is in the lower right cell (n, m).
Input
The first line contains three integers n, m and w (2 β€ n, m β€ 2 β
10^3, 1 β€ w β€ 10^9), where n and m are city size, w is time during which Dima moves between unoccupied cells.
The next n lines each contain m numbers (-1 β€ a_{ij} β€ 10^9) β descriptions of cells.
It is guaranteed that the cells (1, 1) and (n, m) are free.
Output
Output the minimum time it will take for Dima to get to school. If he cannot get to school at all, then output "-1".
Example
Input
5 5 1
0 -1 0 1 -1
0 20 0 0 -1
-1 -1 -1 -1 -1
3 0 0 0 0
-1 0 0 0 0
Output
14
Note
Explanation for the first sample:
<image>
Tags: brute force, dfs and similar, graphs, greedy, implementation, shortest paths
Correct Solution:
```
import io,os
input = io.BytesIO(os.read(0, os.fstat(0).st_size)).readline
from collections import deque
m,n,w = map(int,input().split())
grid = []
for i in range(m):
temp = list(map(int,input().split()))
grid.append(temp)
#visited_s = [[0 for j in range(n)] for i in range(m)]
#visited_e = [[0 for j in range(n)] for i in range(m)]
visited_s = [0 for i in range(m*n)]
visited_e = [0 for i in range(m*n)]
visited_s[0] = 1
visited_e[-1] = 1
startp = float('inf')
endp = float('inf')
noportal = float('inf')
start = deque()
end = deque()
direc = [[0,-1],[0,1],[-1,0],[1,0]]
start.append([0,0])
end.append([m*n-1,0])
if grid[0][0]>0: startp = grid[0][0]
if grid[m-1][n-1]>0: endp = grid[m-1][n-1]
while start:
[index,cost] = start.popleft()
x = index//n
y = index%n
for d in range(4):
newx = x + direc[d][0]
newy = y + direc[d][1]
if newx<0 or newx>=m or newy<0 or newy>=n: continue
newindex = newx*n+newy
# print(newx,newy,newindex)
if grid[newx][newy]==-1: continue
if visited_s[newindex]>0: continue
visited_s[newindex] = 1
start.append([newindex,cost+w])
if grid[newx][newy]>0: startp = min(startp,cost+w+grid[newx][newy])
if newindex==m*n-1: noportal = cost+w
#print(visited_s)
while end:
[index,cost] = end.popleft()
x = index//n
y = index%n
for d in range(4):
newx = x + direc[d][0]
newy = y + direc[d][1]
if newx<0 or newx>=m or newy<0 or newy>=n: continue
newindex = newx*n+newy
if grid[newx][newy]==-1: continue
if visited_e[newindex]>0: continue
if cost+w>=endp: continue
if cost+w>=noportal-startp: continue
visited_e[newindex] = 1
end.append([newindex,cost+w])
if grid[newx][newy]>0: endp = min(endp,cost+w+grid[newx][newy])
#print(startp,endp)
#print(ds,de)
ans = min(noportal, startp+endp)
if ans==float('inf'):
ans = -1
print(ans)
```
| 90,380 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Dima overslept the alarm clock, which was supposed to raise him to school.
Dima wonders if he will have time to come to the first lesson. To do this, he needs to know the minimum time it will take him to get from home to school.
The city where Dima lives is a rectangular field of n Γ m size. Each cell (i, j) on this field is denoted by one number a_{ij}:
* The number -1 means that the passage through the cell is prohibited;
* The number 0 means that the cell is free and Dima can walk though it.
* The number x (1 β€ x β€ 10^9) means that the cell contains a portal with a cost of x. A cell with a portal is also considered free.
From any portal, Dima can go to any other portal, while the time of moving from the portal (i, j) to the portal (x, y) corresponds to the sum of their costs a_{ij} + a_{xy}.
In addition to moving between portals, Dima can also move between unoccupied cells adjacent to one side in time w. In particular, he can enter a cell with a portal and not use it.
Initially, Dima is in the upper-left cell (1, 1), and the school is in the lower right cell (n, m).
Input
The first line contains three integers n, m and w (2 β€ n, m β€ 2 β
10^3, 1 β€ w β€ 10^9), where n and m are city size, w is time during which Dima moves between unoccupied cells.
The next n lines each contain m numbers (-1 β€ a_{ij} β€ 10^9) β descriptions of cells.
It is guaranteed that the cells (1, 1) and (n, m) are free.
Output
Output the minimum time it will take for Dima to get to school. If he cannot get to school at all, then output "-1".
Example
Input
5 5 1
0 -1 0 1 -1
0 20 0 0 -1
-1 -1 -1 -1 -1
3 0 0 0 0
-1 0 0 0 0
Output
14
Note
Explanation for the first sample:
<image>
Tags: brute force, dfs and similar, graphs, greedy, implementation, shortest paths
Correct Solution:
```
'''
from bisect import bisect,bisect_left
from collections import *
from heapq import *
from math import gcd,ceil,sqrt,floor,inf
from itertools import *
from operator import add,mul,sub,xor,truediv,floordiv
from functools import *
'''
#------------------------------------------------------------------------
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().split())
def RLL(): return list(map(int, sys.stdin.readline().split()))
def N(): return int(input())
def A(n):return [0]*n
def AI(n,x): return [x]*n
def A2(n,m): return [[0]*m for i in range(n)]
def G(n): return [[] for i in range(n)]
def GP(it): return [[ch,len(list(g))] for ch,g in groupby(it)]
#------------------------------------------------------------------------
#from random import randint
from collections import deque
from math import inf
dxy=[(-1, 0), (0, -1), (0, 1), (1, 0)]
def bfs(s):
dis=[inf]*sz
dis[s]=0
q=deque([s])
while q:
u=q.popleft()
i,j=divmod(u,m)
for dx,dy in dxy:
ni=i+dx
nj=j+dy
if 0<=ni<n and 0<=nj<m and res[ni][nj]!=-1:
v=ni*m+nj
if dis[v]>dis[u]+1:
dis[v]=dis[u]+1
q.append(v)
return dis
t=1
for i in range(t):
n,m,w=RL()
sz=n*m
res=[list(map(int, sys.stdin.readline().split())) for i in range(n)]
ds=bfs(0)
de=bfs(sz-1)
ans=ds[sz-1]*w
fi=se=inf
for i in range(n):
for j in range(m):
if res[i][j]>0:
fi=min(fi,ds[i*m+j]*w+res[i][j])
se=min(se,de[i*m+j]*w+res[i][j])
ans=min(ans,fi+se)
if ans==inf:
ans=-1
print(ans)
'''
sys.setrecursionlimit(200000)
import threading
threading.stack_size(10**8)
t=threading.Thr
ead(target=main)
t.start()
t.join()
'''
```
| 90,381 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Dima overslept the alarm clock, which was supposed to raise him to school.
Dima wonders if he will have time to come to the first lesson. To do this, he needs to know the minimum time it will take him to get from home to school.
The city where Dima lives is a rectangular field of n Γ m size. Each cell (i, j) on this field is denoted by one number a_{ij}:
* The number -1 means that the passage through the cell is prohibited;
* The number 0 means that the cell is free and Dima can walk though it.
* The number x (1 β€ x β€ 10^9) means that the cell contains a portal with a cost of x. A cell with a portal is also considered free.
From any portal, Dima can go to any other portal, while the time of moving from the portal (i, j) to the portal (x, y) corresponds to the sum of their costs a_{ij} + a_{xy}.
In addition to moving between portals, Dima can also move between unoccupied cells adjacent to one side in time w. In particular, he can enter a cell with a portal and not use it.
Initially, Dima is in the upper-left cell (1, 1), and the school is in the lower right cell (n, m).
Input
The first line contains three integers n, m and w (2 β€ n, m β€ 2 β
10^3, 1 β€ w β€ 10^9), where n and m are city size, w is time during which Dima moves between unoccupied cells.
The next n lines each contain m numbers (-1 β€ a_{ij} β€ 10^9) β descriptions of cells.
It is guaranteed that the cells (1, 1) and (n, m) are free.
Output
Output the minimum time it will take for Dima to get to school. If he cannot get to school at all, then output "-1".
Example
Input
5 5 1
0 -1 0 1 -1
0 20 0 0 -1
-1 -1 -1 -1 -1
3 0 0 0 0
-1 0 0 0 0
Output
14
Note
Explanation for the first sample:
<image>
Tags: brute force, dfs and similar, graphs, greedy, implementation, shortest paths
Correct Solution:
```
#!/usr/bin/env python3
import io
import os
from collections import deque
# input = sys.stdin.readline # to read input quickly
from math import inf
input = io.BytesIO(os.read(0, os.fstat(0).st_size)).readline
# available on Google, AtCoder Python3, not available on Codeforces
# import numpy as np
# import scipy
M9 = 10**9 + 7 # 998244353
yes, no = "YES", "NO"
d4 = [(1,0),(0,1),(-1,0),(0,-1)]
# d8 = [(1,0),(1,1),(0,1),(-1,1),(-1,0),(-1,-1),(0,-1),(1,-1)]
# d6 = [(2,0),(1,1),(-1,1),(-2,0),(-1,-1),(1,-1)] # hexagonal layout
MAXINT = inf
# ---------------------------- template ends here ----------------------------
def solve_(mrr, w, nrows, ncols):
# your solution here
size = nrows*ncols
def dfs(source, size):
# start from zero
stack = deque([source])
dist = [MAXINT]*size
dist[source] = 0
while stack:
loc = stack.popleft()
x,y = divmod(loc, ncols)
for dx,dy in d4:
xx = x+dx
yy = y+dy
new_loc = xx*ncols+yy
if 0 <= xx < nrows and 0 <= yy < ncols and dist[new_loc] == MAXINT and mrr[new_loc] >= 0:
dist[new_loc] = dist[loc] + 1
stack.append(new_loc)
return dist
dist_from_start = dfs(0, size)
dist_from_dest = dfs(size-1, size)
# log(dist_from_start)
# log(dist_from_dest)
tele_from_start = inf
tele_from_dest = inf
for x in range(nrows):
for y in range(ncols):
loc = x*ncols + y
if mrr[loc] > 0:
tele_from_start = min(tele_from_start, mrr[loc] + w * dist_from_start[loc])
tele_from_dest = min(tele_from_dest, mrr[loc] + w * dist_from_dest[loc])
minres = min(dist_from_start[size-1]*w, tele_from_start+tele_from_dest)
if minres == inf:
return -1
return minres
for case_num in [0]: # no loop over test case
# read one line and parse each word as an integer
n,m,w = list(map(int,input().split()))
# lst = list(map(int,input().split()))
# lst = minus_one(lst)
# read multiple rows
# arr = read_strings(k) # and return as a list of str
mrr = [int(x) for i in range(n) for x in input().split()]
# mrr = read_matrix(n) # and return as a list of list of int
# mrr = minus_one_matrix(mrr)
res = solve_(mrr, w, n, m) # include input here
print(int(res))
```
| 90,382 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Dima overslept the alarm clock, which was supposed to raise him to school.
Dima wonders if he will have time to come to the first lesson. To do this, he needs to know the minimum time it will take him to get from home to school.
The city where Dima lives is a rectangular field of n Γ m size. Each cell (i, j) on this field is denoted by one number a_{ij}:
* The number -1 means that the passage through the cell is prohibited;
* The number 0 means that the cell is free and Dima can walk though it.
* The number x (1 β€ x β€ 10^9) means that the cell contains a portal with a cost of x. A cell with a portal is also considered free.
From any portal, Dima can go to any other portal, while the time of moving from the portal (i, j) to the portal (x, y) corresponds to the sum of their costs a_{ij} + a_{xy}.
In addition to moving between portals, Dima can also move between unoccupied cells adjacent to one side in time w. In particular, he can enter a cell with a portal and not use it.
Initially, Dima is in the upper-left cell (1, 1), and the school is in the lower right cell (n, m).
Input
The first line contains three integers n, m and w (2 β€ n, m β€ 2 β
10^3, 1 β€ w β€ 10^9), where n and m are city size, w is time during which Dima moves between unoccupied cells.
The next n lines each contain m numbers (-1 β€ a_{ij} β€ 10^9) β descriptions of cells.
It is guaranteed that the cells (1, 1) and (n, m) are free.
Output
Output the minimum time it will take for Dima to get to school. If he cannot get to school at all, then output "-1".
Example
Input
5 5 1
0 -1 0 1 -1
0 20 0 0 -1
-1 -1 -1 -1 -1
3 0 0 0 0
-1 0 0 0 0
Output
14
Note
Explanation for the first sample:
<image>
Tags: brute force, dfs and similar, graphs, greedy, implementation, shortest paths
Correct Solution:
```
#!/usr/bin/env python3
import io
import os
from collections import deque
# input = sys.stdin.readline # to read input quickly
from math import inf
input = io.BytesIO(os.read(0, os.fstat(0).st_size)).readline
# available on Google, AtCoder Python3, not available on Codeforces
# import numpy as np
# import scipy
M9 = 10**9 + 7 # 998244353
yes, no = "YES", "NO"
d4 = [(1,0),(0,1),(-1,0),(0,-1)]
# d8 = [(1,0),(1,1),(0,1),(-1,1),(-1,0),(-1,-1),(0,-1),(1,-1)]
# d6 = [(2,0),(1,1),(-1,1),(-2,0),(-1,-1),(1,-1)] # hexagonal layout
MAXINT = inf
# ---------------------------- template ends here ----------------------------
def solve_(mrr, w, nrows, ncols):
# your solution here
size = nrows*ncols
def dfs(source, size):
# start from zero
stack = deque([source])
dist = [MAXINT]*size
dist[source] = 0
while stack:
loc = stack.popleft()
x,y = divmod(loc, ncols)
for dx,dy in d4:
xx = x+dx
yy = y+dy
if 0 <= xx < nrows and 0 <= yy < ncols:
new_loc = xx*ncols+yy
if dist[new_loc] == MAXINT and mrr[new_loc] >= 0:
dist[new_loc] = dist[loc] + w
stack.append(new_loc)
return dist
dist_from_start = dfs(0, size)
dist_from_dest = dfs(size-1, size)
# log(dist_from_start)
# log(dist_from_dest)
tele_from_start = inf
tele_from_dest = inf
for x in range(nrows):
for y in range(ncols):
loc = x*ncols + y
if mrr[loc] > 0:
tele_from_start = min(tele_from_start, mrr[loc] + dist_from_start[loc])
tele_from_dest = min(tele_from_dest, mrr[loc] + dist_from_dest[loc])
minres = min(dist_from_start[size-1], tele_from_start+tele_from_dest)
if minres == inf:
return -1
return minres
for case_num in [0]: # no loop over test case
# read one line and parse each word as an integer
n,m,w = list(map(int,input().split()))
# lst = list(map(int,input().split()))
# lst = minus_one(lst)
w = float(w)
# read multiple rows
# arr = read_strings(k) # and return as a list of str
mrr = [float(x) for i in range(n) for x in input().split()]
# mrr = read_matrix(n) # and return as a list of list of int
# mrr = minus_one_matrix(mrr)
res = solve_(mrr, w, n, m) # include input here
print(int(res))
```
| 90,383 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Dima overslept the alarm clock, which was supposed to raise him to school.
Dima wonders if he will have time to come to the first lesson. To do this, he needs to know the minimum time it will take him to get from home to school.
The city where Dima lives is a rectangular field of n Γ m size. Each cell (i, j) on this field is denoted by one number a_{ij}:
* The number -1 means that the passage through the cell is prohibited;
* The number 0 means that the cell is free and Dima can walk though it.
* The number x (1 β€ x β€ 10^9) means that the cell contains a portal with a cost of x. A cell with a portal is also considered free.
From any portal, Dima can go to any other portal, while the time of moving from the portal (i, j) to the portal (x, y) corresponds to the sum of their costs a_{ij} + a_{xy}.
In addition to moving between portals, Dima can also move between unoccupied cells adjacent to one side in time w. In particular, he can enter a cell with a portal and not use it.
Initially, Dima is in the upper-left cell (1, 1), and the school is in the lower right cell (n, m).
Input
The first line contains three integers n, m and w (2 β€ n, m β€ 2 β
10^3, 1 β€ w β€ 10^9), where n and m are city size, w is time during which Dima moves between unoccupied cells.
The next n lines each contain m numbers (-1 β€ a_{ij} β€ 10^9) β descriptions of cells.
It is guaranteed that the cells (1, 1) and (n, m) are free.
Output
Output the minimum time it will take for Dima to get to school. If he cannot get to school at all, then output "-1".
Example
Input
5 5 1
0 -1 0 1 -1
0 20 0 0 -1
-1 -1 -1 -1 -1
3 0 0 0 0
-1 0 0 0 0
Output
14
Note
Explanation for the first sample:
<image>
Tags: brute force, dfs and similar, graphs, greedy, implementation, shortest paths
Correct Solution:
```
#!/usr/bin/env python3
import io
import os
from collections import deque
# input = sys.stdin.readline # to read input quickly
from math import inf
input = io.BytesIO(os.read(0, os.fstat(0).st_size)).readline
# available on Google, AtCoder Python3, not available on Codeforces
# import numpy as np
# import scipy
M9 = 10**9 + 7 # 998244353
yes, no = "YES", "NO"
d4 = [(1,0),(0,1),(-1,0),(0,-1)]
# d8 = [(1,0),(1,1),(0,1),(-1,1),(-1,0),(-1,-1),(0,-1),(1,-1)]
# d6 = [(2,0),(1,1),(-1,1),(-2,0),(-1,-1),(1,-1)] # hexagonal layout
MAXINT = inf
# if testing locally, print to terminal with a different color
# OFFLINE_TEST = getpass.getuser() == "hkmac"
OFFLINE_TEST = False # codechef does not allow getpass
def log(*args):
if OFFLINE_TEST:
print('\033[36m', *args, '\033[0m', file=sys.stderr)
def solve(*args):
# screen input
if OFFLINE_TEST:
log("----- solving ------")
log(*args)
log("----- ------- ------")
return solve_(*args)
def read_matrix(rows):
return [list(map(int,input().split())) for _ in range(rows)]
def read_strings(rows):
return [input().strip() for _ in range(rows)]
def minus_one(arr):
return [x-1 for x in arr]
def minus_one_matrix(mrr):
return [[x-1 for x in row] for row in mrr]
# ---------------------------- template ends here ----------------------------
def solve_(mrr, w, nrows, ncols):
# your solution here
size = nrows*ncols
def dfs(source, size):
# start from zero
stack = deque([source])
dist = [MAXINT]*size
dist[source] = 0
while stack:
loc = stack.popleft()
x,y = divmod(loc, ncols)
for dx,dy in d4:
xx = x+dx
yy = y+dy
new_loc = xx*ncols+yy
if 0 <= xx < nrows and 0 <= yy < ncols and dist[new_loc] == MAXINT and mrr[new_loc] >= 0:
dist[new_loc] = dist[loc] + 1
stack.append(new_loc)
return dist
dist_from_start = dfs(0, size)
dist_from_dest = dfs(size-1, size)
# log(dist_from_start)
# log(dist_from_dest)
tele_from_start = inf
tele_from_dest = inf
for x in range(nrows):
for y in range(ncols):
loc = x*ncols + y
if mrr[loc] > 0:
tele_from_start = min(tele_from_start, mrr[loc] + w * dist_from_start[loc])
tele_from_dest = min(tele_from_dest, mrr[loc] + w * dist_from_dest[loc])
minres = min(dist_from_start[size-1]*w, tele_from_start+tele_from_dest)
if minres == inf:
return -1
return minres
for case_num in [0]: # no loop over test case
# for case_num in range(100): # if the number of test cases is specified
# for case_num in range(int(input())):
# read line as an integer
# k = int(input())
# read line as a string
# srr = input().strip()
# read one line and parse each word as a string
# lst = input().split()
# read one line and parse each word as an integer
n,m,w = list(map(int,input().split()))
# lst = list(map(int,input().split()))
# lst = minus_one(lst)
# read multiple rows
# arr = read_strings(k) # and return as a list of str
mrr = [int(x) for i in range(n) for x in input().split()]
# mrr = read_matrix(n) # and return as a list of list of int
# mrr = minus_one_matrix(mrr)
res = solve(mrr, w, n, m) # include input here
# print length if applicable
# print(len(res))
# parse result
# res = " ".join(str(x) for x in res)
# res = "\n".join(str(x) for x in res)
# res = "\n".join(" ".join(str(x) for x in row) for row in res)
# print result
# print("Case #{}: {}".format(case_num+1, res)) # Google and Facebook - case number required
print(res)
```
| 90,384 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Dima overslept the alarm clock, which was supposed to raise him to school.
Dima wonders if he will have time to come to the first lesson. To do this, he needs to know the minimum time it will take him to get from home to school.
The city where Dima lives is a rectangular field of n Γ m size. Each cell (i, j) on this field is denoted by one number a_{ij}:
* The number -1 means that the passage through the cell is prohibited;
* The number 0 means that the cell is free and Dima can walk though it.
* The number x (1 β€ x β€ 10^9) means that the cell contains a portal with a cost of x. A cell with a portal is also considered free.
From any portal, Dima can go to any other portal, while the time of moving from the portal (i, j) to the portal (x, y) corresponds to the sum of their costs a_{ij} + a_{xy}.
In addition to moving between portals, Dima can also move between unoccupied cells adjacent to one side in time w. In particular, he can enter a cell with a portal and not use it.
Initially, Dima is in the upper-left cell (1, 1), and the school is in the lower right cell (n, m).
Input
The first line contains three integers n, m and w (2 β€ n, m β€ 2 β
10^3, 1 β€ w β€ 10^9), where n and m are city size, w is time during which Dima moves between unoccupied cells.
The next n lines each contain m numbers (-1 β€ a_{ij} β€ 10^9) β descriptions of cells.
It is guaranteed that the cells (1, 1) and (n, m) are free.
Output
Output the minimum time it will take for Dima to get to school. If he cannot get to school at all, then output "-1".
Example
Input
5 5 1
0 -1 0 1 -1
0 20 0 0 -1
-1 -1 -1 -1 -1
3 0 0 0 0
-1 0 0 0 0
Output
14
Note
Explanation for the first sample:
<image>
Tags: brute force, dfs and similar, graphs, greedy, implementation, shortest paths
Correct Solution:
```
import io,os
input = io.BytesIO(os.read(0, os.fstat(0).st_size)).readline
from collections import deque
m,n,w = map(int,input().split())
grid = []
for i in range(m):
temp = list(map(int,input().split()))
grid.append(temp)
#visited_s = [[0 for j in range(n)] for i in range(m)]
#visited_e = [[0 for j in range(n)] for i in range(m)]
visited_s = [0 for i in range(m*n)]
visited_e = [0 for i in range(m*n)]
visited_s[0] = 1
visited_e[-1] = 1
startp = 10**18 #float('inf')
endp = 10**18 #float('inf')
noportal = 10**18 #float('inf')
start = deque()
end = deque()
direc = [[0,-1],[0,1],[-1,0],[1,0]]
start.append([0,0])
end.append([m*n-1,0])
if grid[0][0]>0: startp = grid[0][0]
if grid[m-1][n-1]>0: endp = grid[m-1][n-1]
while start:
[index,cost] = start.popleft()
x = index//n
y = index%n
for d in range(4):
newx = x + direc[d][0]
newy = y + direc[d][1]
if newx<0 or newx>=m or newy<0 or newy>=n: continue
newindex = newx*n+newy
# print(newx,newy,newindex)
if grid[newx][newy]==-1: continue
if visited_s[newindex]>0: continue
visited_s[newindex] = 1
start.append([newindex,cost+w])
if grid[newx][newy]>0: startp = min(startp,cost+w+grid[newx][newy])
if newindex==m*n-1: noportal = cost+w
#print(visited_s)
while end:
[index,cost] = end.popleft()
x = index//n
y = index%n
for d in range(4):
newx = x + direc[d][0]
newy = y + direc[d][1]
if newx<0 or newx>=m or newy<0 or newy>=n: continue
newindex = newx*n+newy
if grid[newx][newy]==-1: continue
if visited_e[newindex]>0: continue
if cost+w>=endp: continue
if cost+w>=noportal-startp: continue
visited_e[newindex] = 1
end.append([newindex,cost+w])
if grid[newx][newy]>0: endp = min(endp,cost+w+grid[newx][newy])
#print(startp,endp)
#print(ds,de)
ans = min(noportal, startp+endp)
if ans==10**18:
ans = -1
print(ans)
```
| 90,385 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Dima overslept the alarm clock, which was supposed to raise him to school.
Dima wonders if he will have time to come to the first lesson. To do this, he needs to know the minimum time it will take him to get from home to school.
The city where Dima lives is a rectangular field of n Γ m size. Each cell (i, j) on this field is denoted by one number a_{ij}:
* The number -1 means that the passage through the cell is prohibited;
* The number 0 means that the cell is free and Dima can walk though it.
* The number x (1 β€ x β€ 10^9) means that the cell contains a portal with a cost of x. A cell with a portal is also considered free.
From any portal, Dima can go to any other portal, while the time of moving from the portal (i, j) to the portal (x, y) corresponds to the sum of their costs a_{ij} + a_{xy}.
In addition to moving between portals, Dima can also move between unoccupied cells adjacent to one side in time w. In particular, he can enter a cell with a portal and not use it.
Initially, Dima is in the upper-left cell (1, 1), and the school is in the lower right cell (n, m).
Input
The first line contains three integers n, m and w (2 β€ n, m β€ 2 β
10^3, 1 β€ w β€ 10^9), where n and m are city size, w is time during which Dima moves between unoccupied cells.
The next n lines each contain m numbers (-1 β€ a_{ij} β€ 10^9) β descriptions of cells.
It is guaranteed that the cells (1, 1) and (n, m) are free.
Output
Output the minimum time it will take for Dima to get to school. If he cannot get to school at all, then output "-1".
Example
Input
5 5 1
0 -1 0 1 -1
0 20 0 0 -1
-1 -1 -1 -1 -1
3 0 0 0 0
-1 0 0 0 0
Output
14
Note
Explanation for the first sample:
<image>
Tags: brute force, dfs and similar, graphs, greedy, implementation, shortest paths
Correct Solution:
```
#!/usr/bin/env python3
import io
import os
from collections import deque
# input = sys.stdin.readline # to read input quickly
from math import inf
input = io.BytesIO(os.read(0, os.fstat(0).st_size)).readline
# available on Google, AtCoder Python3, not available on Codeforces
# import numpy as np
# import scipy
M9 = 10**9 + 7 # 998244353
yes, no = "YES", "NO"
d4 = [(1,0),(0,1),(-1,0),(0,-1)]
# d8 = [(1,0),(1,1),(0,1),(-1,1),(-1,0),(-1,-1),(0,-1),(1,-1)]
# d6 = [(2,0),(1,1),(-1,1),(-2,0),(-1,-1),(1,-1)] # hexagonal layout
MAXINT = inf
# ---------------------------- template ends here ----------------------------
def solve_(mrr, w, nrows, ncols):
# your solution here
size = nrows*ncols
def dfs(source, size):
# start from zero
stack = deque([source])
dist = [MAXINT]*size
dist[source] = 0
while stack:
loc = stack.popleft()
x,y = divmod(loc, ncols)
for dx,dy in d4:
xx = x+dx
yy = y+dy
new_loc = xx*ncols+yy
if 0 <= xx < nrows and 0 <= yy < ncols and dist[new_loc] == MAXINT and mrr[new_loc] >= 0:
dist[new_loc] = dist[loc] + 1
stack.append(new_loc)
return dist
dist_from_start = dfs(0, size)
dist_from_dest = dfs(size-1, size)
# log(dist_from_start)
# log(dist_from_dest)
tele_from_start = inf
tele_from_dest = inf
for x in range(nrows):
for y in range(ncols):
loc = x*ncols + y
if mrr[loc] > 0:
tele_from_start = min(tele_from_start, mrr[loc] + w * dist_from_start[loc])
tele_from_dest = min(tele_from_dest, mrr[loc] + w * dist_from_dest[loc])
minres = min(dist_from_start[size-1]*w, tele_from_start+tele_from_dest)
if minres == inf:
return -1
return minres
for case_num in [0]: # no loop over test case
# read one line and parse each word as an integer
n,m,w = list(map(int,input().split()))
# lst = list(map(int,input().split()))
# lst = minus_one(lst)
w = float(w)
# read multiple rows
# arr = read_strings(k) # and return as a list of str
mrr = [float(x) for i in range(n) for x in input().split()]
# mrr = read_matrix(n) # and return as a list of list of int
# mrr = minus_one_matrix(mrr)
res = solve_(mrr, w, n, m) # include input here
print(int(res))
```
| 90,386 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Dima overslept the alarm clock, which was supposed to raise him to school.
Dima wonders if he will have time to come to the first lesson. To do this, he needs to know the minimum time it will take him to get from home to school.
The city where Dima lives is a rectangular field of n Γ m size. Each cell (i, j) on this field is denoted by one number a_{ij}:
* The number -1 means that the passage through the cell is prohibited;
* The number 0 means that the cell is free and Dima can walk though it.
* The number x (1 β€ x β€ 10^9) means that the cell contains a portal with a cost of x. A cell with a portal is also considered free.
From any portal, Dima can go to any other portal, while the time of moving from the portal (i, j) to the portal (x, y) corresponds to the sum of their costs a_{ij} + a_{xy}.
In addition to moving between portals, Dima can also move between unoccupied cells adjacent to one side in time w. In particular, he can enter a cell with a portal and not use it.
Initially, Dima is in the upper-left cell (1, 1), and the school is in the lower right cell (n, m).
Input
The first line contains three integers n, m and w (2 β€ n, m β€ 2 β
10^3, 1 β€ w β€ 10^9), where n and m are city size, w is time during which Dima moves between unoccupied cells.
The next n lines each contain m numbers (-1 β€ a_{ij} β€ 10^9) β descriptions of cells.
It is guaranteed that the cells (1, 1) and (n, m) are free.
Output
Output the minimum time it will take for Dima to get to school. If he cannot get to school at all, then output "-1".
Example
Input
5 5 1
0 -1 0 1 -1
0 20 0 0 -1
-1 -1 -1 -1 -1
3 0 0 0 0
-1 0 0 0 0
Output
14
Note
Explanation for the first sample:
<image>
Tags: brute force, dfs and similar, graphs, greedy, implementation, shortest paths
Correct Solution:
```
from collections import deque
from math import inf
import io
import os
input = io.BytesIO(os.read(0, os.fstat(0).st_size)).readline
(n,m,w) = [int(x) for x in input().split()]
M = [int(x) for i in range(n) for x in input().split()]
X = n*m
ds = [inf]*X
de = [inf]*X
ss = inf
ee = inf
aa = inf
ds[0] = de[-1] = 0
dr = [(0,-1),(0,1),(-1,0),(1,0)]
q = deque([0])
while q:
x = q.popleft()
i,j = divmod(x,m)
d = ds[x]
for di,dj in dr:
h = i+di
k = j+dj
if 0>h or 0>k or h>=n or k>=m or M[h*m+k] == -1:
continue
y = h*m + k
if ds[y] < inf:
continue
ds[y] = d+1
q.append(y)
q = deque([n*m-1])
while q:
x = q.popleft()
i,j = divmod(x,m)
d = de[x]
for di,dj in dr:
h = i+di
k = j+dj
if 0>h or 0>k or h>=n or k>=m or M[h*m+k] == -1:
continue
y = h*m + k
if de[y] < inf:
continue
de[y] = d+1
q.append(y)
for i in range(n):
for j in range(m):
x = i*m+j
if M[x] > 0:
ss = min(ss,ds[x]*w + M[x])
ee = min(ee,de[x]*w + M[x])
aa = ds[-1]*w
ans = min(aa,ss+ee)
ans = ans if ans < inf else -1
print(ans)
```
| 90,387 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Dima overslept the alarm clock, which was supposed to raise him to school.
Dima wonders if he will have time to come to the first lesson. To do this, he needs to know the minimum time it will take him to get from home to school.
The city where Dima lives is a rectangular field of n Γ m size. Each cell (i, j) on this field is denoted by one number a_{ij}:
* The number -1 means that the passage through the cell is prohibited;
* The number 0 means that the cell is free and Dima can walk though it.
* The number x (1 β€ x β€ 10^9) means that the cell contains a portal with a cost of x. A cell with a portal is also considered free.
From any portal, Dima can go to any other portal, while the time of moving from the portal (i, j) to the portal (x, y) corresponds to the sum of their costs a_{ij} + a_{xy}.
In addition to moving between portals, Dima can also move between unoccupied cells adjacent to one side in time w. In particular, he can enter a cell with a portal and not use it.
Initially, Dima is in the upper-left cell (1, 1), and the school is in the lower right cell (n, m).
Input
The first line contains three integers n, m and w (2 β€ n, m β€ 2 β
10^3, 1 β€ w β€ 10^9), where n and m are city size, w is time during which Dima moves between unoccupied cells.
The next n lines each contain m numbers (-1 β€ a_{ij} β€ 10^9) β descriptions of cells.
It is guaranteed that the cells (1, 1) and (n, m) are free.
Output
Output the minimum time it will take for Dima to get to school. If he cannot get to school at all, then output "-1".
Example
Input
5 5 1
0 -1 0 1 -1
0 20 0 0 -1
-1 -1 -1 -1 -1
3 0 0 0 0
-1 0 0 0 0
Output
14
Note
Explanation for the first sample:
<image>
Submitted Solution:
```
#!/usr/bin/env python3
import io
import os
from collections import deque
# input = sys.stdin.readline # to read input quickly
from math import inf
input = io.BytesIO(os.read(0, os.fstat(0).st_size)).readline
# available on Google, AtCoder Python3, not available on Codeforces
# import numpy as np
# import scipy
M9 = 10**9 + 7 # 998244353
yes, no = "YES", "NO"
d4 = [(1,0),(0,1),(-1,0),(0,-1)]
# d8 = [(1,0),(1,1),(0,1),(-1,1),(-1,0),(-1,-1),(0,-1),(1,-1)]
# d6 = [(2,0),(1,1),(-1,1),(-2,0),(-1,-1),(1,-1)] # hexagonal layout
MAXINT = inf
# if testing locally, print to terminal with a different color
# OFFLINE_TEST = getpass.getuser() == "hkmac"
OFFLINE_TEST = False # codechef does not allow getpass
def log(*args):
if OFFLINE_TEST:
print('\033[36m', *args, '\033[0m', file=sys.stderr)
def solve(*args):
# screen input
if OFFLINE_TEST:
log("----- solving ------")
log(*args)
log("----- ------- ------")
return solve_(*args)
def read_matrix(rows):
return [list(map(int,input().split())) for _ in range(rows)]
def read_strings(rows):
return [input().strip() for _ in range(rows)]
def minus_one(arr):
return [x-1 for x in arr]
def minus_one_matrix(mrr):
return [[x-1 for x in row] for row in mrr]
# ---------------------------- template ends here ----------------------------
def solve_(mrr, w, nrows, ncols):
# your solution here
size = nrows*ncols
def dfs(source, size):
# start from zero
stack = deque([source])
dist = [MAXINT]*size
dist[source] = 0
while stack:
loc = stack.popleft()
x,y = divmod(loc, ncols)
for dx,dy in d4:
xx = x+dx
yy = y+dy
new_loc = xx*ncols+yy
if 0 <= xx < nrows and 0 <= yy < ncols and dist[new_loc] == MAXINT and mrr[new_loc] >= 0:
dist[new_loc] = dist[loc] + 1
stack.append(new_loc)
return dist
dist_from_start = dfs(0, size)
dist_from_dest = dfs(size-1, size)
# log(dist_from_start)
# log(dist_from_dest)
tele_from_start = inf
tele_from_dest = inf
for x in range(nrows):
for y in range(ncols):
loc = x*ncols + y
if mrr[loc] > 0:
tele_from_start = min(tele_from_start, mrr[loc] + w * dist_from_start[loc])
tele_from_dest = min(tele_from_dest, mrr[loc] + w * dist_from_dest[loc])
minres = min(dist_from_start[size-1]*w, tele_from_start+tele_from_dest)
if minres == inf:
return -1
return minres
for case_num in [0]: # no loop over test case
# for case_num in range(100): # if the number of test cases is specified
# for case_num in range(int(input())):
# read line as an integer
# k = int(input())
# read line as a string
# srr = input().strip()
# read one line and parse each word as a string
# lst = input().split()
# read one line and parse each word as an integer
n,m,w = list(map(int,input().split()))
# lst = list(map(int,input().split()))
# lst = minus_one(lst)
# read multiple rows
# arr = read_strings(k) # and return as a list of str
mrr = [int(x) for i in range(n) for x in input().split()]
# mrr = read_matrix(n) # and return as a list of list of int
# mrr = minus_one_matrix(mrr)
res = solve(mrr, w, n, m) # include input here
# print length if applicable
# print(len(res))
# parse result
# res = " ".join(str(x) for x in res)
# res = "\n".join(str(x) for x in res)
# res = "\n".join(" ".join(str(x) for x in row) for row in res)
# print result
# print("Case #{}: {}".format(case_num+1, res)) # Google and Facebook - case number required
print(int(res))
```
Yes
| 90,388 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Dima overslept the alarm clock, which was supposed to raise him to school.
Dima wonders if he will have time to come to the first lesson. To do this, he needs to know the minimum time it will take him to get from home to school.
The city where Dima lives is a rectangular field of n Γ m size. Each cell (i, j) on this field is denoted by one number a_{ij}:
* The number -1 means that the passage through the cell is prohibited;
* The number 0 means that the cell is free and Dima can walk though it.
* The number x (1 β€ x β€ 10^9) means that the cell contains a portal with a cost of x. A cell with a portal is also considered free.
From any portal, Dima can go to any other portal, while the time of moving from the portal (i, j) to the portal (x, y) corresponds to the sum of their costs a_{ij} + a_{xy}.
In addition to moving between portals, Dima can also move between unoccupied cells adjacent to one side in time w. In particular, he can enter a cell with a portal and not use it.
Initially, Dima is in the upper-left cell (1, 1), and the school is in the lower right cell (n, m).
Input
The first line contains three integers n, m and w (2 β€ n, m β€ 2 β
10^3, 1 β€ w β€ 10^9), where n and m are city size, w is time during which Dima moves between unoccupied cells.
The next n lines each contain m numbers (-1 β€ a_{ij} β€ 10^9) β descriptions of cells.
It is guaranteed that the cells (1, 1) and (n, m) are free.
Output
Output the minimum time it will take for Dima to get to school. If he cannot get to school at all, then output "-1".
Example
Input
5 5 1
0 -1 0 1 -1
0 20 0 0 -1
-1 -1 -1 -1 -1
3 0 0 0 0
-1 0 0 0 0
Output
14
Note
Explanation for the first sample:
<image>
Submitted Solution:
```
'''
from bisect import bisect,bisect_left
from collections import *
from heapq import *
from math import gcd,ceil,sqrt,floor,inf
from itertools import *
from operator import add,mul,sub,xor,truediv,floordiv
from functools import *
'''
#------------------------------------------------------------------------
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().split())
def RLL(): return list(map(int, sys.stdin.readline().split()))
def N(): return int(input())
def A(n):return [0]*n
def AI(n,x): return [x]*n
def A2(n,m): return [[0]*m for i in range(n)]
def G(n): return [[] for i in range(n)]
def GP(it): return [[ch,len(list(g))] for ch,g in groupby(it)]
#------------------------------------------------------------------------
#from random import randint
from collections import deque
from math import inf
dxy=[(-1, 0), (0, -1), (0, 1), (1, 0)]
def bfs(s):
dis=AI(sz,inf)
dis[s]=0
q=deque([s])
while q:
u=q.popleft()
i,j=divmod(u,m)
for dx,dy in dxy:
ni=i+dx
nj=j+dy
if 0<=ni<n and 0<=nj<m and res[ni][nj]!=-1:
v=ni*m+nj
if dis[v]>dis[u]+1:
dis[v]=dis[u]+1
q.append(v)
return dis
t=1
for i in range(t):
n,m,w=RL()
sz=n*m
res=[]
for i in range(n):
res.append(RLL())
ds=bfs(0)
de=bfs(sz-1)
ans=ds[sz-1]*w
fi=se=inf
for i in range(n):
for j in range(m):
if res[i][j]>0:
fi=min(fi,ds[i*m+j]*w+res[i][j])
se=min(se,de[i*m+j]*w+res[i][j])
ans=min(ans,fi+se)
if ans==inf:
ans=-1
print(ans)
'''
sys.setrecursionlimit(200000)
import threading
threading.stack_size(10**8)
t=threading.Thr
ead(target=main)
t.start()
t.join()
'''
```
Yes
| 90,389 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Dima overslept the alarm clock, which was supposed to raise him to school.
Dima wonders if he will have time to come to the first lesson. To do this, he needs to know the minimum time it will take him to get from home to school.
The city where Dima lives is a rectangular field of n Γ m size. Each cell (i, j) on this field is denoted by one number a_{ij}:
* The number -1 means that the passage through the cell is prohibited;
* The number 0 means that the cell is free and Dima can walk though it.
* The number x (1 β€ x β€ 10^9) means that the cell contains a portal with a cost of x. A cell with a portal is also considered free.
From any portal, Dima can go to any other portal, while the time of moving from the portal (i, j) to the portal (x, y) corresponds to the sum of their costs a_{ij} + a_{xy}.
In addition to moving between portals, Dima can also move between unoccupied cells adjacent to one side in time w. In particular, he can enter a cell with a portal and not use it.
Initially, Dima is in the upper-left cell (1, 1), and the school is in the lower right cell (n, m).
Input
The first line contains three integers n, m and w (2 β€ n, m β€ 2 β
10^3, 1 β€ w β€ 10^9), where n and m are city size, w is time during which Dima moves between unoccupied cells.
The next n lines each contain m numbers (-1 β€ a_{ij} β€ 10^9) β descriptions of cells.
It is guaranteed that the cells (1, 1) and (n, m) are free.
Output
Output the minimum time it will take for Dima to get to school. If he cannot get to school at all, then output "-1".
Example
Input
5 5 1
0 -1 0 1 -1
0 20 0 0 -1
-1 -1 -1 -1 -1
3 0 0 0 0
-1 0 0 0 0
Output
14
Note
Explanation for the first sample:
<image>
Submitted Solution:
```
import io, os
from collections import deque
from math import inf
def solve(R, C, W, grid):
drdc = [(-1, 0), (0, -1), (0, 1), (1, 0)]
def bfs(source, N):
q = deque([source]);dist = [inf] * N;dist[source] = 0.0
while q:
node = q.popleft();d = dist[node];r, c = divmod(node, C)
for dr, dc in drdc:
nr = r + dr;nc = c + dc
if 0 <= nr < R and 0 <= nc < C and grid[nr * C + nc] != -1:
nbr = nr * C + nc
if dist[nbr] == inf:q.append(nbr);dist[nbr] = d + 1
return dist
dist1 = bfs(0, R * C);dist2 = bfs(R * C - 1, R * C);best = dist1[R * C - 1] * W;smallest1 = inf;smallest2 = inf
for r in range(R):
for c in range(C):
if grid[r * C + c] > 0:smallest1 = min(smallest1, grid[r * C + c] + W * dist1[r * C + c]);smallest2 = min(smallest2, grid[r * C + c] + W * dist2[r * C + c])
best = min(best, smallest1 + smallest2);return -1 if best == inf else int(best)
input = io.BytesIO(os.read(0, os.fstat(0).st_size)).readline;(N, M, W) = [int(x) for x in input().split()];print(solve(N, M, W, [int(x) for i in range(N) for x in input().split()]))
```
Yes
| 90,390 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Dima overslept the alarm clock, which was supposed to raise him to school.
Dima wonders if he will have time to come to the first lesson. To do this, he needs to know the minimum time it will take him to get from home to school.
The city where Dima lives is a rectangular field of n Γ m size. Each cell (i, j) on this field is denoted by one number a_{ij}:
* The number -1 means that the passage through the cell is prohibited;
* The number 0 means that the cell is free and Dima can walk though it.
* The number x (1 β€ x β€ 10^9) means that the cell contains a portal with a cost of x. A cell with a portal is also considered free.
From any portal, Dima can go to any other portal, while the time of moving from the portal (i, j) to the portal (x, y) corresponds to the sum of their costs a_{ij} + a_{xy}.
In addition to moving between portals, Dima can also move between unoccupied cells adjacent to one side in time w. In particular, he can enter a cell with a portal and not use it.
Initially, Dima is in the upper-left cell (1, 1), and the school is in the lower right cell (n, m).
Input
The first line contains three integers n, m and w (2 β€ n, m β€ 2 β
10^3, 1 β€ w β€ 10^9), where n and m are city size, w is time during which Dima moves between unoccupied cells.
The next n lines each contain m numbers (-1 β€ a_{ij} β€ 10^9) β descriptions of cells.
It is guaranteed that the cells (1, 1) and (n, m) are free.
Output
Output the minimum time it will take for Dima to get to school. If he cannot get to school at all, then output "-1".
Example
Input
5 5 1
0 -1 0 1 -1
0 20 0 0 -1
-1 -1 -1 -1 -1
3 0 0 0 0
-1 0 0 0 0
Output
14
Note
Explanation for the first sample:
<image>
Submitted Solution:
```
# Author : nitish420 --------------------------------------------------------------------
import os
import sys
from io import BytesIO, IOBase
from collections import deque
def main():
n,m,w=map(int,input().split())
graph=[-1]
for _ in range(n):
graph+=list(map(int,input().split()))
graph.append(-1)
start=1
end=n*m
direction=[-1,1,-m,m]
vis_start=[0]*(n*m+2)
vis_end=[0]*(n*m+2)
vis_start[1]=1
vis_end[n*m]=1
portStart=10**16
portEnd=10**16
noPort=10**16
if graph[1]>0:portStart=graph[1]
if graph[n*m]>0:portEnd=graph[n*m]
start=deque([(1,0)])
end=deque([(n*m,0)])
# print(graph)
while start:
z,c=start.popleft()
for i in range(4):
new=z+direction[i]
if new<=0 or new>n*m:
continue
if graph[new]==-1 or vis_start[new]:
continue
if (not (direction[i]==-1 and new%m==0)) and (not (direction[i]==1 and new%m==1)):
vis_start[new]=1
start.append((new,c+w))
if graph[new]>0:
portStart=min(portStart,c+w+graph[new])
if new==n*m:
noPort=c+w
while end:
z,c=end.popleft()
for i in range(4):
new=z+direction[i]
if new<=0 or new>n*m:
continue
if graph[new]==-1 or vis_end[new]:
continue
if (not (direction[i]==-1 and new%m==0)) and (not (direction[i]==1 and new%m==1)):
vis_end[new]=1
end.append((new,c+w))
if graph[new]>0:
portEnd=min(portEnd,c+w+graph[new])
if new==1:
noPort=min(noPort,c+w)
ans=min(portEnd+portStart,noPort)
if ans==10**16:
print(-1)
else:
print(ans)
# 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')
# endregion
if __name__ == '__main__':
main()
```
Yes
| 90,391 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Dima overslept the alarm clock, which was supposed to raise him to school.
Dima wonders if he will have time to come to the first lesson. To do this, he needs to know the minimum time it will take him to get from home to school.
The city where Dima lives is a rectangular field of n Γ m size. Each cell (i, j) on this field is denoted by one number a_{ij}:
* The number -1 means that the passage through the cell is prohibited;
* The number 0 means that the cell is free and Dima can walk though it.
* The number x (1 β€ x β€ 10^9) means that the cell contains a portal with a cost of x. A cell with a portal is also considered free.
From any portal, Dima can go to any other portal, while the time of moving from the portal (i, j) to the portal (x, y) corresponds to the sum of their costs a_{ij} + a_{xy}.
In addition to moving between portals, Dima can also move between unoccupied cells adjacent to one side in time w. In particular, he can enter a cell with a portal and not use it.
Initially, Dima is in the upper-left cell (1, 1), and the school is in the lower right cell (n, m).
Input
The first line contains three integers n, m and w (2 β€ n, m β€ 2 β
10^3, 1 β€ w β€ 10^9), where n and m are city size, w is time during which Dima moves between unoccupied cells.
The next n lines each contain m numbers (-1 β€ a_{ij} β€ 10^9) β descriptions of cells.
It is guaranteed that the cells (1, 1) and (n, m) are free.
Output
Output the minimum time it will take for Dima to get to school. If he cannot get to school at all, then output "-1".
Example
Input
5 5 1
0 -1 0 1 -1
0 20 0 0 -1
-1 -1 -1 -1 -1
3 0 0 0 0
-1 0 0 0 0
Output
14
Note
Explanation for the first sample:
<image>
Submitted Solution:
```
from collections import deque
m,n,w = map(int,input().split())
grid = []
for i in range(m):
temp = list(map(int,input().split()))
grid.append(temp)
ds = [[float('inf') for j in range(n)] for i in range(m)]
de = [[float('inf') for j in range(n)] for i in range(m)]
ds[0][0] = 0
de[m-1][n-1] = 0
startp = float('inf')
endp = float('inf')
start = deque()
end = deque()
direc = [[0,-1],[0,1],[-1,0],[1,0]]
start.append([0,0,0])
end.append([m-1,n-1,0])
while start:
[x,y,cost] = start.popleft()
for d in range(4):
newx = x + direc[d][0]
newy = y + direc[d][1]
if newx<0 or newx>=m or newy<0 or newy>=n: continue
if grid[newx][newy]==-1: continue
if ds[newx][newy] > cost+w:
ds[newx][newy] = cost+w
start.append([newx,newy,cost+w])
if grid[newx][newy]>0: startp = min(startp,cost+w+grid[newx][newy])
while end:
[x,y,cost] = end.popleft()
for d in range(4):
newx = x + direc[d][0]
newy = y + direc[d][1]
if newx<0 or newx>=m or newy<0 or newy>=n: continue
if grid[newx][newy]==-1: continue
if de[newx][newy] > cost+w:
de[newx][newy] = cost+w
end.append([newx,newy,cost+w])
if grid[newx][newy]>0: endp = min(endp,cost+w+grid[newx][newy])
#print(startp,endp)
#print(ds,de)
ans = min(ds[m-1][n-1], startp+endp)
print(ans)
```
No
| 90,392 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Dima overslept the alarm clock, which was supposed to raise him to school.
Dima wonders if he will have time to come to the first lesson. To do this, he needs to know the minimum time it will take him to get from home to school.
The city where Dima lives is a rectangular field of n Γ m size. Each cell (i, j) on this field is denoted by one number a_{ij}:
* The number -1 means that the passage through the cell is prohibited;
* The number 0 means that the cell is free and Dima can walk though it.
* The number x (1 β€ x β€ 10^9) means that the cell contains a portal with a cost of x. A cell with a portal is also considered free.
From any portal, Dima can go to any other portal, while the time of moving from the portal (i, j) to the portal (x, y) corresponds to the sum of their costs a_{ij} + a_{xy}.
In addition to moving between portals, Dima can also move between unoccupied cells adjacent to one side in time w. In particular, he can enter a cell with a portal and not use it.
Initially, Dima is in the upper-left cell (1, 1), and the school is in the lower right cell (n, m).
Input
The first line contains three integers n, m and w (2 β€ n, m β€ 2 β
10^3, 1 β€ w β€ 10^9), where n and m are city size, w is time during which Dima moves between unoccupied cells.
The next n lines each contain m numbers (-1 β€ a_{ij} β€ 10^9) β descriptions of cells.
It is guaranteed that the cells (1, 1) and (n, m) are free.
Output
Output the minimum time it will take for Dima to get to school. If he cannot get to school at all, then output "-1".
Example
Input
5 5 1
0 -1 0 1 -1
0 20 0 0 -1
-1 -1 -1 -1 -1
3 0 0 0 0
-1 0 0 0 0
Output
14
Note
Explanation for the first sample:
<image>
Submitted Solution:
```
# by the authority of GOD author: manhar singh sachdev #
import os,sys
from io import BytesIO,IOBase
from collections import deque
def main():
n,m,w = map(int,input().split())
arr = [list(map(int,input().split()))+[-1] for _ in range(n)]
arr.append([-1]*(m+1))
dis = [[10**20]*m for _ in range(n)]
dis1 = [[10**20]*m for _ in range(n)]
dx,dy = [-1,1,0,0],[0,0,-1,1]
curr = deque([(0,0)])
dis[0][0] = 0
while len(curr):
x,y = curr.popleft()
for i,j in zip(dx,dy):
a,b = x+i,y+j
if arr[a][b] != -1 and dis[a][b] == 10**20:
dis[a][b] = dis[x][y]+1
curr.append((a,b))
curr = deque([(n-1,m-1)])
dis1[n-1][m-1] = 0
while len(curr):
x,y = curr.popleft()
for i,j in zip(dx,dy):
a,b = x+i,y+j
if arr[a][b] != -1 and dis1[a][b] == 10**20:
dis1[a][b] = dis1[x][y]+1
curr.append((a,b))
por = []
# dis from 0,0 ; dis from n,m ; value
cou = 1
for i in range(n):
for j in range(m):
if arr[i][j] > 0:
por.append((dis[i][j]*w,dis1[i][j]*w,arr[i][j],cou))
cou += 1
if not len(por):
if dis[n-1][m-1] != 10**20:
print((n+m-2)*w)
else:
print(-1)
exit()
por1 = sorted(por,key=lambda xx:xx[0]+xx[2])
por2 = sorted(por,key=lambda xx:xx[1]+xx[2])
if por1[0][3] == por2[0][3]:
if len(por) == 1:
print(-1)
else:
print(min(por1[1][0]+por1[1][2]+por2[0][1]+por2[0][2],
por1[0][0]+por1[0][2]+por2[1][1]+por2[1][2]))
else:
print(por1[0][0]+por2[0][1]+por1[0][2]+por2[0][2])
# 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()
```
No
| 90,393 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Dima overslept the alarm clock, which was supposed to raise him to school.
Dima wonders if he will have time to come to the first lesson. To do this, he needs to know the minimum time it will take him to get from home to school.
The city where Dima lives is a rectangular field of n Γ m size. Each cell (i, j) on this field is denoted by one number a_{ij}:
* The number -1 means that the passage through the cell is prohibited;
* The number 0 means that the cell is free and Dima can walk though it.
* The number x (1 β€ x β€ 10^9) means that the cell contains a portal with a cost of x. A cell with a portal is also considered free.
From any portal, Dima can go to any other portal, while the time of moving from the portal (i, j) to the portal (x, y) corresponds to the sum of their costs a_{ij} + a_{xy}.
In addition to moving between portals, Dima can also move between unoccupied cells adjacent to one side in time w. In particular, he can enter a cell with a portal and not use it.
Initially, Dima is in the upper-left cell (1, 1), and the school is in the lower right cell (n, m).
Input
The first line contains three integers n, m and w (2 β€ n, m β€ 2 β
10^3, 1 β€ w β€ 10^9), where n and m are city size, w is time during which Dima moves between unoccupied cells.
The next n lines each contain m numbers (-1 β€ a_{ij} β€ 10^9) β descriptions of cells.
It is guaranteed that the cells (1, 1) and (n, m) are free.
Output
Output the minimum time it will take for Dima to get to school. If he cannot get to school at all, then output "-1".
Example
Input
5 5 1
0 -1 0 1 -1
0 20 0 0 -1
-1 -1 -1 -1 -1
3 0 0 0 0
-1 0 0 0 0
Output
14
Note
Explanation for the first sample:
<image>
Submitted Solution:
```
from sys import stdin, stdout
import heapq
from collections import defaultdict
import math
import bisect
def main():
n,m,w = list(map(int, stdin.readline().split()))
mp = []
for _ in range(n):
mp.append(list(map(int, stdin.readline().split())))
mn_start = math.inf
stack = [(0,0)]
visited = [[False] * m for _ in range(n)]
step = 0
to_fin = math.inf
while stack:
tmp = []
for i,j in stack:
visited[i][j] = True
if mp[i][j] != 0:
mn_start = min(mn_start, step * w + mp[i][j])
if i == n - 1 and j == m - 1:
to_fin = w * step
break
if i and mp[i-1][j] != -1 and not visited[i-1][j]:
tmp.append([i-1, j])
if j and mp[i][j-1] != -1 and not visited[i][j-1]:
tmp.append([i, j-1])
if i < n-1 and mp[i+1][j] != -1 and not visited[i+1][j]:
tmp.append([i+1, j])
if j < m-1 and mp[i][j+1] != -1 and not visited[i][j+1]:
tmp.append([i, j+1])
if to_fin != math.inf:
break
if to_fin != math.inf:
break
step += 1
stack = tmp
mn_s = mn_start
mn_start = math.inf
stack = [(n-1, m-1)]
visited = [[False] * m for _ in range(n)]
step = 0
while stack:
tmp = []
for i, j in stack:
visited[i][j] = True
if mp[i][j] != 0:
mn_start = min(mn_start, step * w + mp[i][j])
if i == 0 and j == 0:
to_fin = w * step
break
if i and mp[i - 1][j] != -1 and not visited[i - 1][j]:
tmp.append([i - 1, j])
if j and mp[i][j - 1] != -1 and not visited[i][j - 1]:
tmp.append([i, j - 1])
if i < n - 1 and mp[i + 1][j] != -1 and not visited[i + 1][j]:
tmp.append([i + 1, j])
if j < m - 1 and mp[i][j + 1] != -1 and not visited[i][j + 1]:
tmp.append([i, j + 1])
if to_fin != math.inf:
break
if to_fin != math.inf:
break
step += 1
stack = tmp
ans = min(to_fin, mn_s + mn_start)
if ans == math.inf:
stdout.write("-1")
else:
stdout.write(str(ans))
main()
```
No
| 90,394 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Dima overslept the alarm clock, which was supposed to raise him to school.
Dima wonders if he will have time to come to the first lesson. To do this, he needs to know the minimum time it will take him to get from home to school.
The city where Dima lives is a rectangular field of n Γ m size. Each cell (i, j) on this field is denoted by one number a_{ij}:
* The number -1 means that the passage through the cell is prohibited;
* The number 0 means that the cell is free and Dima can walk though it.
* The number x (1 β€ x β€ 10^9) means that the cell contains a portal with a cost of x. A cell with a portal is also considered free.
From any portal, Dima can go to any other portal, while the time of moving from the portal (i, j) to the portal (x, y) corresponds to the sum of their costs a_{ij} + a_{xy}.
In addition to moving between portals, Dima can also move between unoccupied cells adjacent to one side in time w. In particular, he can enter a cell with a portal and not use it.
Initially, Dima is in the upper-left cell (1, 1), and the school is in the lower right cell (n, m).
Input
The first line contains three integers n, m and w (2 β€ n, m β€ 2 β
10^3, 1 β€ w β€ 10^9), where n and m are city size, w is time during which Dima moves between unoccupied cells.
The next n lines each contain m numbers (-1 β€ a_{ij} β€ 10^9) β descriptions of cells.
It is guaranteed that the cells (1, 1) and (n, m) are free.
Output
Output the minimum time it will take for Dima to get to school. If he cannot get to school at all, then output "-1".
Example
Input
5 5 1
0 -1 0 1 -1
0 20 0 0 -1
-1 -1 -1 -1 -1
3 0 0 0 0
-1 0 0 0 0
Output
14
Note
Explanation for the first sample:
<image>
Submitted Solution:
```
n,m,w = map(int,input().split())
M = []
for _ in range(n):
M.append(list(map(int,input().split())))
# find closest portal to end and start respectively
end = [n-1,m-1]
d = 0
# cost to go to the end and the cost of portal
best_end_cost = float('inf')
cost_back_to_start = float('inf')
q = [[n-1,m-1]]
visited = [[False]*m for _ in range(n)]
visited[n-1][m-1] = True
while q:
next_q = []
for i,j in q:
for h,k in [(i-1,j),(i+1,j),(i,j-1),(i,j+1)]:
if 0<=h<n and 0<=k<m and M[h][k] != -1 and not visited[h][k]:
if h == 0 and k == 0:
cost_back_to_start = d + w
if M[h][k]>0 and M[h][k] + d + w < best_end_cost:
best_end_cost = M[h][k] + d +w
visited[h][k] = True
next_q.append([h,k])
d += w
q = next_q
best_start_cost = float('inf')
q = [[0,0]]
visited = [[False]*m for _ in range(n)]
visited[0][0] = True
d = 0
while q:
next_q = []
for i,j in q:
for h,k in [(i-1,j),(i+1,j),(i,j-1),(i,j+1)]:
if 0<=h<n and 0<=k<m and M[h][k] != -1 and not visited[h][k]:
if M[h][k]>0 and M[h][k] + d + w < best_start_cost:
best_start_cost = M[h][k] + d + w
visited[h][k] = True
next_q.append([h,k])
d += w
q = next_q
ans = min(cost_back_to_start, best_start_cost + best_end_cost)
ans = ans if ans != float('inf') else -1
print(ans)
```
No
| 90,395 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Two players play a game. The game is played on a rectangular board with n Γ m squares. At the beginning of the game two different squares of the board have two chips. The first player's goal is to shift the chips to the same square. The second player aims to stop the first one with a tube of superglue.
We'll describe the rules of the game in more detail.
The players move in turns. The first player begins.
With every move the first player chooses one of his unglued chips, and shifts it one square to the left, to the right, up or down. It is not allowed to move a chip beyond the board edge. At the beginning of a turn some squares of the board may be covered with a glue. The first player can move the chip to such square, in this case the chip gets tightly glued and cannot move any longer.
At each move the second player selects one of the free squares (which do not contain a chip or a glue) and covers it with superglue. The glue dries long and squares covered with it remain sticky up to the end of the game.
If, after some move of the first player both chips are in the same square, then the first player wins. If the first player cannot make a move (both of his chips are glued), then the second player wins. Note that the situation where the second player cannot make a move is impossible β he can always spread the glue on the square from which the first player has just moved the chip.
We will further clarify the case where both chips are glued and are in the same square. In this case the first player wins as the game ends as soon as both chips are in the same square, and the condition of the loss (the inability to move) does not arise.
You know the board sizes and the positions of the two chips on it. At the beginning of the game all board squares are glue-free. Find out who wins if the players play optimally.
Input
The first line contains six integers n, m, x1, y1, x2, y2 β the board sizes and the coordinates of the first and second chips, correspondingly (1 β€ n, m β€ 100; 2 β€ n Γ m; 1 β€ x1, x2 β€ n; 1 β€ y1, y2 β€ m). The numbers in the line are separated by single spaces.
It is guaranteed that the chips are located in different squares.
Output
If the first player wins, print "First" without the quotes. Otherwise, print "Second" without the quotes.
Examples
Input
1 6 1 2 1 6
Output
First
Input
6 5 4 3 2 1
Output
First
Input
10 10 1 1 10 10
Output
Second
Tags: combinatorics, constructive algorithms
Correct Solution:
```
n,m,X,Y,x,y=map(int,input().split())
a=[abs(X-x),abs(Y-y)]
a.sort()
print("First" if a[1]<5 and a[0]+a[1]<7 else "Second")
```
| 90,396 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Two players play a game. The game is played on a rectangular board with n Γ m squares. At the beginning of the game two different squares of the board have two chips. The first player's goal is to shift the chips to the same square. The second player aims to stop the first one with a tube of superglue.
We'll describe the rules of the game in more detail.
The players move in turns. The first player begins.
With every move the first player chooses one of his unglued chips, and shifts it one square to the left, to the right, up or down. It is not allowed to move a chip beyond the board edge. At the beginning of a turn some squares of the board may be covered with a glue. The first player can move the chip to such square, in this case the chip gets tightly glued and cannot move any longer.
At each move the second player selects one of the free squares (which do not contain a chip or a glue) and covers it with superglue. The glue dries long and squares covered with it remain sticky up to the end of the game.
If, after some move of the first player both chips are in the same square, then the first player wins. If the first player cannot make a move (both of his chips are glued), then the second player wins. Note that the situation where the second player cannot make a move is impossible β he can always spread the glue on the square from which the first player has just moved the chip.
We will further clarify the case where both chips are glued and are in the same square. In this case the first player wins as the game ends as soon as both chips are in the same square, and the condition of the loss (the inability to move) does not arise.
You know the board sizes and the positions of the two chips on it. At the beginning of the game all board squares are glue-free. Find out who wins if the players play optimally.
Input
The first line contains six integers n, m, x1, y1, x2, y2 β the board sizes and the coordinates of the first and second chips, correspondingly (1 β€ n, m β€ 100; 2 β€ n Γ m; 1 β€ x1, x2 β€ n; 1 β€ y1, y2 β€ m). The numbers in the line are separated by single spaces.
It is guaranteed that the chips are located in different squares.
Output
If the first player wins, print "First" without the quotes. Otherwise, print "Second" without the quotes.
Examples
Input
1 6 1 2 1 6
Output
First
Input
6 5 4 3 2 1
Output
First
Input
10 10 1 1 10 10
Output
Second
Tags: combinatorics, constructive algorithms
Correct Solution:
```
n,m,X,Y,x,y=map(int,input().split())
a=[abs(X-x),abs(Y-y)]
a.sort()
print("First" if a[1]<5 and a[0]+a[1]<7 else "Second")
# Made By Mostafa_Khaled
```
| 90,397 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Two players play a game. The game is played on a rectangular board with n Γ m squares. At the beginning of the game two different squares of the board have two chips. The first player's goal is to shift the chips to the same square. The second player aims to stop the first one with a tube of superglue.
We'll describe the rules of the game in more detail.
The players move in turns. The first player begins.
With every move the first player chooses one of his unglued chips, and shifts it one square to the left, to the right, up or down. It is not allowed to move a chip beyond the board edge. At the beginning of a turn some squares of the board may be covered with a glue. The first player can move the chip to such square, in this case the chip gets tightly glued and cannot move any longer.
At each move the second player selects one of the free squares (which do not contain a chip or a glue) and covers it with superglue. The glue dries long and squares covered with it remain sticky up to the end of the game.
If, after some move of the first player both chips are in the same square, then the first player wins. If the first player cannot make a move (both of his chips are glued), then the second player wins. Note that the situation where the second player cannot make a move is impossible β he can always spread the glue on the square from which the first player has just moved the chip.
We will further clarify the case where both chips are glued and are in the same square. In this case the first player wins as the game ends as soon as both chips are in the same square, and the condition of the loss (the inability to move) does not arise.
You know the board sizes and the positions of the two chips on it. At the beginning of the game all board squares are glue-free. Find out who wins if the players play optimally.
Input
The first line contains six integers n, m, x1, y1, x2, y2 β the board sizes and the coordinates of the first and second chips, correspondingly (1 β€ n, m β€ 100; 2 β€ n Γ m; 1 β€ x1, x2 β€ n; 1 β€ y1, y2 β€ m). The numbers in the line are separated by single spaces.
It is guaranteed that the chips are located in different squares.
Output
If the first player wins, print "First" without the quotes. Otherwise, print "Second" without the quotes.
Examples
Input
1 6 1 2 1 6
Output
First
Input
6 5 4 3 2 1
Output
First
Input
10 10 1 1 10 10
Output
Second
Tags: combinatorics, constructive algorithms
Correct Solution:
```
# ------------------- fast io --------------------
import os
import sys
from io import BytesIO, IOBase
BUFSIZE = 8192
class FastIO(IOBase):
newlines = 0
def __init__(self, file):
self._fd = file.fileno()
self.buffer = BytesIO()
self.writable = "x" in file.mode or "r" not in file.mode
self.write = self.buffer.write if self.writable else None
def read(self):
while True:
b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
if not b:
break
ptr = self.buffer.tell()
self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr)
self.newlines = 0
return self.buffer.read()
def readline(self):
while self.newlines == 0:
b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
self.newlines = b.count(b"\n") + (not b)
ptr = self.buffer.tell()
self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr)
self.newlines -= 1
return self.buffer.readline()
def flush(self):
if self.writable:
os.write(self._fd, self.buffer.getvalue())
self.buffer.truncate(0), self.buffer.seek(0)
class IOWrapper(IOBase):
def __init__(self, file):
self.buffer = FastIO(file)
self.flush = self.buffer.flush
self.writable = self.buffer.writable
self.write = lambda s: self.buffer.write(s.encode("ascii"))
self.read = lambda: self.buffer.read().decode("ascii")
self.readline = lambda: self.buffer.readline().decode("ascii")
sys.stdin, sys.stdout = IOWrapper(sys.stdin), IOWrapper(sys.stdout)
input = lambda: sys.stdin.readline().rstrip("\r\n")
# ------------------- fast io --------------------
from math import gcd, ceil
def prod(a, mod=10**9+7):
ans = 1
for each in a:
ans = (ans * each) % mod
return ans
def lcm(a, b): return a * b // gcd(a, b)
def binary(x, length=16):
y = bin(x)[2:]
return y if len(y) >= length else "0" * (length - len(y)) + y
for _ in range(int(input()) if not True else 1):
#n = int(input())
#n, k = map(int, input().split())
n,m,x1,y1,x2,y2 = map(int, input().split())
#c, d = map(int, input().split())
#a = list(map(int, input().split()))
#b = list(map(int, input().split()))
#s = input()
x, y = abs(x2-x1), abs(y2-y1)
x, y = min(x,y), max(x,y)
if [x,y] in [[0,0], [0,1], [0,2], [0,3], [0,4],
[1,1], [1,2], [1,3], [1,4],
[2,2], [2,3], [2,4],
[3,3]]:
print("First")
else:
print("Second")
```
| 90,398 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Two players play a game. The game is played on a rectangular board with n Γ m squares. At the beginning of the game two different squares of the board have two chips. The first player's goal is to shift the chips to the same square. The second player aims to stop the first one with a tube of superglue.
We'll describe the rules of the game in more detail.
The players move in turns. The first player begins.
With every move the first player chooses one of his unglued chips, and shifts it one square to the left, to the right, up or down. It is not allowed to move a chip beyond the board edge. At the beginning of a turn some squares of the board may be covered with a glue. The first player can move the chip to such square, in this case the chip gets tightly glued and cannot move any longer.
At each move the second player selects one of the free squares (which do not contain a chip or a glue) and covers it with superglue. The glue dries long and squares covered with it remain sticky up to the end of the game.
If, after some move of the first player both chips are in the same square, then the first player wins. If the first player cannot make a move (both of his chips are glued), then the second player wins. Note that the situation where the second player cannot make a move is impossible β he can always spread the glue on the square from which the first player has just moved the chip.
We will further clarify the case where both chips are glued and are in the same square. In this case the first player wins as the game ends as soon as both chips are in the same square, and the condition of the loss (the inability to move) does not arise.
You know the board sizes and the positions of the two chips on it. At the beginning of the game all board squares are glue-free. Find out who wins if the players play optimally.
Input
The first line contains six integers n, m, x1, y1, x2, y2 β the board sizes and the coordinates of the first and second chips, correspondingly (1 β€ n, m β€ 100; 2 β€ n Γ m; 1 β€ x1, x2 β€ n; 1 β€ y1, y2 β€ m). The numbers in the line are separated by single spaces.
It is guaranteed that the chips are located in different squares.
Output
If the first player wins, print "First" without the quotes. Otherwise, print "Second" without the quotes.
Examples
Input
1 6 1 2 1 6
Output
First
Input
6 5 4 3 2 1
Output
First
Input
10 10 1 1 10 10
Output
Second
Tags: combinatorics, constructive algorithms
Correct Solution:
```
n,m,x1,y1,x2,y2 = map(int, input().split())
n = abs(x1 - x2)
m = abs(y1 - y2)
if n > 4 or m > 4:
print("Second")
elif n <= 3 and m <= 3:
print("First")
elif min(n, m) <= 2:
print("First")
else:
print("Second")
```
| 90,399 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.