message stringlengths 2 22.8k | message_type stringclasses 2 values | message_id int64 0 1 | conversation_id int64 16 109k | cluster float64 1 1 | __index_level_0__ int64 32 217k |
|---|---|---|---|---|---|
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
There is a double-track line (up and down are separate lines and pass each other everywhere). There are 11 stations on this line, including the terminal station, and each station is called by the section number shown in the figure.
<image>
Trains depart from both terminal stations on this line at the same time and run without stopping along the way. Create a program that reads the length of each section and the speed of the two trains and outputs the number of the section where the trains pass each other in each case. However, if you pass each other just at the station, the smaller number of the section numbers on both sides will be output. In addition, the length of the train and the length of the station cannot be ignored.
Input
Multiple datasets are given. Each dataset is given in the following format.
l1, l2, l3, l4, l5, l6, l7, l8, l9, l10, v1, v2
li (1 ≤ li ≤ 2,000) is an integer representing the length (km) of the interval i. v1 is the speed of the train departing from the terminal station on the section 1 side (km / h), and v2 is the speed of the train departing from the terminal station on the section 10 side (km / h) (1 ≤ v1, v2) ≤ 2,000).
The number of datasets does not exceed 50.
Output
For each data set, the number of the section where the train passes is output on one line.
Example
Input
1,1,1,1,1,1,1,1,1,1,40,60
1,1,1,1,1,3,3,3,3,3,50,50
10,10,10,10,10,10,10,10,10,10,50,49
Output
4
7
6
Submitted Solution:
```
while 1:
try:
a = list(map(float, input().split(',')))
dis = sum(a[:10])
x = a[10] * dis / (a[10] + a[11])
for i in range(0, 11):
if x <= sum(a[:i]):
print(i)
break
except:
break
``` | instruction | 0 | 41,111 | 1 | 82,222 |
Yes | output | 1 | 41,111 | 1 | 82,223 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
There is a double-track line (up and down are separate lines and pass each other everywhere). There are 11 stations on this line, including the terminal station, and each station is called by the section number shown in the figure.
<image>
Trains depart from both terminal stations on this line at the same time and run without stopping along the way. Create a program that reads the length of each section and the speed of the two trains and outputs the number of the section where the trains pass each other in each case. However, if you pass each other just at the station, the smaller number of the section numbers on both sides will be output. In addition, the length of the train and the length of the station cannot be ignored.
Input
Multiple datasets are given. Each dataset is given in the following format.
l1, l2, l3, l4, l5, l6, l7, l8, l9, l10, v1, v2
li (1 ≤ li ≤ 2,000) is an integer representing the length (km) of the interval i. v1 is the speed of the train departing from the terminal station on the section 1 side (km / h), and v2 is the speed of the train departing from the terminal station on the section 10 side (km / h) (1 ≤ v1, v2) ≤ 2,000).
The number of datasets does not exceed 50.
Output
For each data set, the number of the section where the train passes is output on one line.
Example
Input
1,1,1,1,1,1,1,1,1,1,40,60
1,1,1,1,1,3,3,3,3,3,50,50
10,10,10,10,10,10,10,10,10,10,50,49
Output
4
7
6
Submitted Solution:
```
import sys
f = sys.stdin
for line in f:
line = list(map(int, line.split(',')))
l = line[:10]
v1, v2 = line[10:]
for i in range(1, len(l)):
l[i] += l[i - 1]
t = l[-1] / (v1 + v2)
dist = v1 * t
for i in range(len(l)):
if l[i] >= dist:
print(i + 1)
break
``` | instruction | 0 | 41,112 | 1 | 82,224 |
Yes | output | 1 | 41,112 | 1 | 82,225 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
There is a double-track line (up and down are separate lines and pass each other everywhere). There are 11 stations on this line, including the terminal station, and each station is called by the section number shown in the figure.
<image>
Trains depart from both terminal stations on this line at the same time and run without stopping along the way. Create a program that reads the length of each section and the speed of the two trains and outputs the number of the section where the trains pass each other in each case. However, if you pass each other just at the station, the smaller number of the section numbers on both sides will be output. In addition, the length of the train and the length of the station cannot be ignored.
Input
Multiple datasets are given. Each dataset is given in the following format.
l1, l2, l3, l4, l5, l6, l7, l8, l9, l10, v1, v2
li (1 ≤ li ≤ 2,000) is an integer representing the length (km) of the interval i. v1 is the speed of the train departing from the terminal station on the section 1 side (km / h), and v2 is the speed of the train departing from the terminal station on the section 10 side (km / h) (1 ≤ v1, v2) ≤ 2,000).
The number of datasets does not exceed 50.
Output
For each data set, the number of the section where the train passes is output on one line.
Example
Input
1,1,1,1,1,1,1,1,1,1,40,60
1,1,1,1,1,3,3,3,3,3,50,50
10,10,10,10,10,10,10,10,10,10,50,49
Output
4
7
6
Submitted Solution:
```
while True:
try:
lst = list(map(int, input().split(",")))
v2 = lst.pop()
v1 = lst.pop()
cum_sum = [0]
acc = 0
for l in lst:
acc += l
cum_sum.append(acc)
cross = acc * v1 / (v1 + v2)
for i in range(1, 11):
if cross <= cum_sum[i]:
print(i)
break
except EOFError:
break
``` | instruction | 0 | 41,113 | 1 | 82,226 |
Yes | output | 1 | 41,113 | 1 | 82,227 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
There is a double-track line (up and down are separate lines and pass each other everywhere). There are 11 stations on this line, including the terminal station, and each station is called by the section number shown in the figure.
<image>
Trains depart from both terminal stations on this line at the same time and run without stopping along the way. Create a program that reads the length of each section and the speed of the two trains and outputs the number of the section where the trains pass each other in each case. However, if you pass each other just at the station, the smaller number of the section numbers on both sides will be output. In addition, the length of the train and the length of the station cannot be ignored.
Input
Multiple datasets are given. Each dataset is given in the following format.
l1, l2, l3, l4, l5, l6, l7, l8, l9, l10, v1, v2
li (1 ≤ li ≤ 2,000) is an integer representing the length (km) of the interval i. v1 is the speed of the train departing from the terminal station on the section 1 side (km / h), and v2 is the speed of the train departing from the terminal station on the section 10 side (km / h) (1 ≤ v1, v2) ≤ 2,000).
The number of datasets does not exceed 50.
Output
For each data set, the number of the section where the train passes is output on one line.
Example
Input
1,1,1,1,1,1,1,1,1,1,40,60
1,1,1,1,1,3,3,3,3,3,50,50
10,10,10,10,10,10,10,10,10,10,50,49
Output
4
7
6
Submitted Solution:
```
while True:
try:
A = list(map(int,input().split(',')))
except EOFError:
break
V1 = A [-2]
V2 = A [-1]
del A [-1]
del A [-1]
for i in range(len(A)):
A [i] *= V1 + V2
point = sum(A) // (V1 + V2) * V1
for i in range(len(A)):
if sum(A [0:i + 1]) >= point:
print(i + 1)
break
``` | instruction | 0 | 41,114 | 1 | 82,228 |
Yes | output | 1 | 41,114 | 1 | 82,229 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
There is a double-track line (up and down are separate lines and pass each other everywhere). There are 11 stations on this line, including the terminal station, and each station is called by the section number shown in the figure.
<image>
Trains depart from both terminal stations on this line at the same time and run without stopping along the way. Create a program that reads the length of each section and the speed of the two trains and outputs the number of the section where the trains pass each other in each case. However, if you pass each other just at the station, the smaller number of the section numbers on both sides will be output. In addition, the length of the train and the length of the station cannot be ignored.
Input
Multiple datasets are given. Each dataset is given in the following format.
l1, l2, l3, l4, l5, l6, l7, l8, l9, l10, v1, v2
li (1 ≤ li ≤ 2,000) is an integer representing the length (km) of the interval i. v1 is the speed of the train departing from the terminal station on the section 1 side (km / h), and v2 is the speed of the train departing from the terminal station on the section 10 side (km / h) (1 ≤ v1, v2) ≤ 2,000).
The number of datasets does not exceed 50.
Output
For each data set, the number of the section where the train passes is output on one line.
Example
Input
1,1,1,1,1,1,1,1,1,1,40,60
1,1,1,1,1,3,3,3,3,3,50,50
10,10,10,10,10,10,10,10,10,10,50,49
Output
4
7
6
Submitted Solution:
```
while True:
try:
inp = list(map(int, input().split(",")))
l = inp[0:10]
l_all = sum(l)
v1 = inp[10]
v2 = inp[11]
l_pass = l_all*v1/(v1 + v2)
for i in range(10):
if sum(l[:i]) >= l_pass:
print(i)
break
except:
break
``` | instruction | 0 | 41,115 | 1 | 82,230 |
No | output | 1 | 41,115 | 1 | 82,231 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
There is a double-track line (up and down are separate lines and pass each other everywhere). There are 11 stations on this line, including the terminal station, and each station is called by the section number shown in the figure.
<image>
Trains depart from both terminal stations on this line at the same time and run without stopping along the way. Create a program that reads the length of each section and the speed of the two trains and outputs the number of the section where the trains pass each other in each case. However, if you pass each other just at the station, the smaller number of the section numbers on both sides will be output. In addition, the length of the train and the length of the station cannot be ignored.
Input
Multiple datasets are given. Each dataset is given in the following format.
l1, l2, l3, l4, l5, l6, l7, l8, l9, l10, v1, v2
li (1 ≤ li ≤ 2,000) is an integer representing the length (km) of the interval i. v1 is the speed of the train departing from the terminal station on the section 1 side (km / h), and v2 is the speed of the train departing from the terminal station on the section 10 side (km / h) (1 ≤ v1, v2) ≤ 2,000).
The number of datasets does not exceed 50.
Output
For each data set, the number of the section where the train passes is output on one line.
Example
Input
1,1,1,1,1,1,1,1,1,1,40,60
1,1,1,1,1,3,3,3,3,3,50,50
10,10,10,10,10,10,10,10,10,10,50,49
Output
4
7
6
Submitted Solution:
```
while True:
try:
l1,l2,l3,l4,l5,l6,l7,l8,l9,l10,v1,v2=map(int,input().split(","))
kyo=0
for i in l1,l2,l3,l4,l5,l6,l7,l8,l9,l10:
kyo +=i
v=v1+v2
x=kyo/v
ans=v1*x
flag=0
for j in l1,l2,l3,l4,l5,l6,l7,l8,l9,l10,0:
if ans>0:
ans -=j
flag +=1
print(ans)
else:
print(flag)
break
except:break
``` | instruction | 0 | 41,116 | 1 | 82,232 |
No | output | 1 | 41,116 | 1 | 82,233 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
There is a double-track line (up and down are separate lines and pass each other everywhere). There are 11 stations on this line, including the terminal station, and each station is called by the section number shown in the figure.
<image>
Trains depart from both terminal stations on this line at the same time and run without stopping along the way. Create a program that reads the length of each section and the speed of the two trains and outputs the number of the section where the trains pass each other in each case. However, if you pass each other just at the station, the smaller number of the section numbers on both sides will be output. In addition, the length of the train and the length of the station cannot be ignored.
Input
Multiple datasets are given. Each dataset is given in the following format.
l1, l2, l3, l4, l5, l6, l7, l8, l9, l10, v1, v2
li (1 ≤ li ≤ 2,000) is an integer representing the length (km) of the interval i. v1 is the speed of the train departing from the terminal station on the section 1 side (km / h), and v2 is the speed of the train departing from the terminal station on the section 10 side (km / h) (1 ≤ v1, v2) ≤ 2,000).
The number of datasets does not exceed 50.
Output
For each data set, the number of the section where the train passes is output on one line.
Example
Input
1,1,1,1,1,1,1,1,1,1,40,60
1,1,1,1,1,3,3,3,3,3,50,50
10,10,10,10,10,10,10,10,10,10,50,49
Output
4
7
6
Submitted Solution:
```
while True :
try:
x=[int(i) for i in input().split(",")]
Len=x[:-2]
ve=x[len(x)-2:]
sum_ve=sum(ve)
k=sum(Len)/sum_ve
count=0
for i in range(len(Len)):
if count<k*ve[0]:
count+=Len[i]
else:
print(i)
break
except EOFError:
break
``` | instruction | 0 | 41,117 | 1 | 82,234 |
No | output | 1 | 41,117 | 1 | 82,235 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
There is a double-track line (up and down are separate lines and pass each other everywhere). There are 11 stations on this line, including the terminal station, and each station is called by the section number shown in the figure.
<image>
Trains depart from both terminal stations on this line at the same time and run without stopping along the way. Create a program that reads the length of each section and the speed of the two trains and outputs the number of the section where the trains pass each other in each case. However, if you pass each other just at the station, the smaller number of the section numbers on both sides will be output. In addition, the length of the train and the length of the station cannot be ignored.
Input
Multiple datasets are given. Each dataset is given in the following format.
l1, l2, l3, l4, l5, l6, l7, l8, l9, l10, v1, v2
li (1 ≤ li ≤ 2,000) is an integer representing the length (km) of the interval i. v1 is the speed of the train departing from the terminal station on the section 1 side (km / h), and v2 is the speed of the train departing from the terminal station on the section 10 side (km / h) (1 ≤ v1, v2) ≤ 2,000).
The number of datasets does not exceed 50.
Output
For each data set, the number of the section where the train passes is output on one line.
Example
Input
1,1,1,1,1,1,1,1,1,1,40,60
1,1,1,1,1,3,3,3,3,3,50,50
10,10,10,10,10,10,10,10,10,10,50,49
Output
4
7
6
Submitted Solution:
```
import sys
def p(i):
if(i==1):
print("One")
elif(i==2):
print("Two")
elif(i==3):
print("Three")
elif(i==4):
print("Four")
elif(i==5):
print("Five")
elif(i==6):
print("Six")
elif(i==7):
print("Seven")
elif(i==8):
print("Eight")
elif(i==9):
print("Nine")
elif(i==10):
print("Ten")
a=[]
for i in range(10):
a.append(-1)
for line in sys.stdin.readlines():
a[0], a[1], a[2], a[3], a[4], a[5], a[6], a[7], a[8], a[9], s1, s2=map(int,line.split(','))
time=sum(a)/(s1+s2)
if(s1<=s2):
d=s1*time
for i in range(10):
if(d>0):
d=d-a[i]
else:
p(i)
break
else:
d=s2*time
for i in range(9,0,-1):
if(d>0):
d=d-a[i]
# print("d:",d)
else:
p(i+2)
break
``` | instruction | 0 | 41,118 | 1 | 82,236 |
No | output | 1 | 41,118 | 1 | 82,237 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Bertown has n junctions and m bidirectional roads. We know that one can get from any junction to any other one by the existing roads.
As there were more and more cars in the city, traffic jams started to pose real problems. To deal with them the government decided to make the traffic one-directional on all the roads, thus easing down the traffic. Your task is to determine whether there is a way to make the traffic one-directional so that there still is the possibility to get from any junction to any other one. If the answer is positive, you should also find one of the possible ways to orient the roads.
Input
The first line contains two space-separated integers n and m (2 ≤ n ≤ 105, n - 1 ≤ m ≤ 3·105) which represent the number of junctions and the roads in the town correspondingly. Then follow m lines, each containing two numbers which describe the roads in the city. Each road is determined by two integers ai and bi (1 ≤ ai, bi ≤ n, ai ≠ bi) — the numbers of junctions it connects.
It is guaranteed that one can get from any junction to any other one along the existing bidirectional roads. Each road connects different junctions, there is no more than one road between each pair of junctions.
Output
If there's no solution, print the single number 0. Otherwise, print m lines each containing two integers pi and qi — each road's orientation. That is the traffic flow will move along a one-directional road from junction pi to junction qi. You can print the roads in any order. If there are several solutions to that problem, print any of them.
Examples
Input
6 8
1 2
2 3
1 3
4 5
4 6
5 6
2 4
3 5
Output
1 2
2 3
3 1
4 5
5 6
6 4
4 2
3 5
Input
6 7
1 2
2 3
1 3
4 5
4 6
5 6
2 4
Output
0 | instruction | 0 | 41,301 | 1 | 82,602 |
Tags: dfs and similar, graphs
Correct Solution:
```
from sys import setrecursionlimit
from collections import defaultdict
from threading import stack_size,Thread
setrecursionlimit(10**6)
stack_size(2**25)
edge=defaultdict(list)
visited=[False]*(100001)
intime=[0]*(100001)
low=[0]*(100001)
l1=[]
bridge=False
timer=0
def DFS(node,parent):
global l1,edge,visited,intime,low,timer,bridge
visited[node]=1
intime[node]=timer
low[node]=timer
timer+=1
for child in edge[node]:
if visited[child]==1:
if child==parent:
pass
else:
low[node]=min(intime[child],low[node])
if (intime[node]>intime[child]):
l1.append([node,child])
else:
DFS(child,node)
if low[child]>intime[node]:
bridge=True
return None
l1.append([node,child])
low[node]=min(low[node],low[child])
def main():
r=lambda:map(int,input().split())
n,m=r()
global edge,visited,intime,low,l1,bridge,timer
for i in range(1,n+1):
edge[i]=[]
visited[i]=0
intime[i]=0
low[i]=0
for _ in range(m):
p,q=r()
edge[p].append(q)
edge[q].append(p)
DFS(1,-1)
if bridge==True:
print(0)
else:
# print(l1)
for i in l1:
print(*i)
if __name__ == "__main__":
Thread(target=main).start()
``` | output | 1 | 41,301 | 1 | 82,603 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Bertown has n junctions and m bidirectional roads. We know that one can get from any junction to any other one by the existing roads.
As there were more and more cars in the city, traffic jams started to pose real problems. To deal with them the government decided to make the traffic one-directional on all the roads, thus easing down the traffic. Your task is to determine whether there is a way to make the traffic one-directional so that there still is the possibility to get from any junction to any other one. If the answer is positive, you should also find one of the possible ways to orient the roads.
Input
The first line contains two space-separated integers n and m (2 ≤ n ≤ 105, n - 1 ≤ m ≤ 3·105) which represent the number of junctions and the roads in the town correspondingly. Then follow m lines, each containing two numbers which describe the roads in the city. Each road is determined by two integers ai and bi (1 ≤ ai, bi ≤ n, ai ≠ bi) — the numbers of junctions it connects.
It is guaranteed that one can get from any junction to any other one along the existing bidirectional roads. Each road connects different junctions, there is no more than one road between each pair of junctions.
Output
If there's no solution, print the single number 0. Otherwise, print m lines each containing two integers pi and qi — each road's orientation. That is the traffic flow will move along a one-directional road from junction pi to junction qi. You can print the roads in any order. If there are several solutions to that problem, print any of them.
Examples
Input
6 8
1 2
2 3
1 3
4 5
4 6
5 6
2 4
3 5
Output
1 2
2 3
3 1
4 5
5 6
6 4
4 2
3 5
Input
6 7
1 2
2 3
1 3
4 5
4 6
5 6
2 4
Output
0 | instruction | 0 | 41,302 | 1 | 82,604 |
Tags: dfs and similar, graphs
Correct Solution:
```
from __future__ import division, print_function
import os
import sys
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
# region fastio
# Credits
# # template credits to cheran-senthil's github Repo
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")
# endregion
def main():
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
import time
class Graph(object):
def __init__(self):
self.neighbours = {}
def __repr__(self):
s = ''
for i in self.neighbours:
s += str(i)+': '+' '.join(map(str,self.neighbours[i])) + '\n'
return s
def add_node(self, node):
self.neighbours[node] = set()
def add_edge(self, edge):
u, v = edge
self.neighbours[u].add(v)
self.neighbours[v].add(u)
@bootstrap
def dfs(self, node, par):
visited[node] = 1
intime[node] = lowtime[node] = timer[0]
timer[0] += 1
for child in self.neighbours[node]:
# if cur node's child is parent than for forward edge it is valid ancestor
if child == par:
continue
# even after checking for parent it is already visited than it is a back edge
if visited[child] == 1:
if intime[node] > intime[child]:
lis.append([node,child])
# This is a back edge
# So we are updating the lowtime of cur node with intime of
lowtime[node] = min(lowtime[node],intime[child])
else:
# This is a forward edge
lis.append([node,child])
yield self.dfs(child, node)
# if low[child]<in[node]
# even if you remove this edge child is still connected from another path. so can't be a bridge
if lowtime[child] > intime[node]:
flag[0] = 0
lowtime[node] = min(lowtime[node],lowtime[child])
yield
def bfs(self, node):
q = queue()
visited[node] = 1
q.append(node)
while q:
cur = q.popleft()
for child in self.neighbours[cur]:
if visited[child] == 0:
q.append(child)
visited[child] = 1
g = Graph()
n,m=map(int,input().split())
for i in range(n):
g.add_node(i+1)
for i in range(m):
x, y = map(int, input().split())
g.add_edge((x, y))
visited = [0] * (n + 1)
intime = [0] * (n + 1)
lowtime = [0] * (n + 1)
timer = [0]
flag = [1]
lis = []
g.dfs(1, -1)
if flag[0]:
for i in lis:
print(' '.join(map(str,i)))
else:
print(0)
if __name__ == "__main__":
main()
``` | output | 1 | 41,302 | 1 | 82,605 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Bertown has n junctions and m bidirectional roads. We know that one can get from any junction to any other one by the existing roads.
As there were more and more cars in the city, traffic jams started to pose real problems. To deal with them the government decided to make the traffic one-directional on all the roads, thus easing down the traffic. Your task is to determine whether there is a way to make the traffic one-directional so that there still is the possibility to get from any junction to any other one. If the answer is positive, you should also find one of the possible ways to orient the roads.
Input
The first line contains two space-separated integers n and m (2 ≤ n ≤ 105, n - 1 ≤ m ≤ 3·105) which represent the number of junctions and the roads in the town correspondingly. Then follow m lines, each containing two numbers which describe the roads in the city. Each road is determined by two integers ai and bi (1 ≤ ai, bi ≤ n, ai ≠ bi) — the numbers of junctions it connects.
It is guaranteed that one can get from any junction to any other one along the existing bidirectional roads. Each road connects different junctions, there is no more than one road between each pair of junctions.
Output
If there's no solution, print the single number 0. Otherwise, print m lines each containing two integers pi and qi — each road's orientation. That is the traffic flow will move along a one-directional road from junction pi to junction qi. You can print the roads in any order. If there are several solutions to that problem, print any of them.
Examples
Input
6 8
1 2
2 3
1 3
4 5
4 6
5 6
2 4
3 5
Output
1 2
2 3
3 1
4 5
5 6
6 4
4 2
3 5
Input
6 7
1 2
2 3
1 3
4 5
4 6
5 6
2 4
Output
0 | instruction | 0 | 41,303 | 1 | 82,606 |
Tags: dfs and similar, graphs
Correct Solution:
```
from sys import stdin,setrecursionlimit
import threading
input = lambda: stdin.readline().rstrip("\r\n")
#from collections import defaultdict as vector
from collections import deque as que
inin = lambda: int(input())
inar = lambda: list(map(int,input().split()))
from collections import defaultdict
adj=defaultdict(list)
visited=[False]*(100001)
intime=[0]*(100001)
outtime=[0]*(100001)
res=[]
bridge=False
timer=0
def dfs(node,par):
global adj, visited, intime, outtime, res, bridge,timer
visited[node]=True
intime[node]=timer
outtime[node]=timer
timer+=1
for j in adj[node]:
if j==par:
continue
if visited[j]:
outtime[node]=min(outtime[node],intime[j])
if intime[node]>intime[j]:
res.append((node,j))
else:
dfs(j,node)
if outtime[j]>intime[node]:
bridge=True
return
res.append((node,j))
outtime[node] = min(outtime[node], outtime[j])
def main():
n,m=map(int,input().split())
global adj,visited,intime,outtime,res,bridge,timer
timer=0
bridge=False
for i in range(m):
u,v=map(int,input().split())
adj[u].append(v)
adj[v].append(u)
dfs(1,-1)
if bridge:
print(0)
else:
for i in range(len(res)):
print(*res[i])
setrecursionlimit(1 << 30)
threading.stack_size(1 << 25)
main_thread = threading.Thread(target=main)
main_thread.start()
main_thread.join()
``` | output | 1 | 41,303 | 1 | 82,607 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Bertown has n junctions and m bidirectional roads. We know that one can get from any junction to any other one by the existing roads.
As there were more and more cars in the city, traffic jams started to pose real problems. To deal with them the government decided to make the traffic one-directional on all the roads, thus easing down the traffic. Your task is to determine whether there is a way to make the traffic one-directional so that there still is the possibility to get from any junction to any other one. If the answer is positive, you should also find one of the possible ways to orient the roads.
Input
The first line contains two space-separated integers n and m (2 ≤ n ≤ 105, n - 1 ≤ m ≤ 3·105) which represent the number of junctions and the roads in the town correspondingly. Then follow m lines, each containing two numbers which describe the roads in the city. Each road is determined by two integers ai and bi (1 ≤ ai, bi ≤ n, ai ≠ bi) — the numbers of junctions it connects.
It is guaranteed that one can get from any junction to any other one along the existing bidirectional roads. Each road connects different junctions, there is no more than one road between each pair of junctions.
Output
If there's no solution, print the single number 0. Otherwise, print m lines each containing two integers pi and qi — each road's orientation. That is the traffic flow will move along a one-directional road from junction pi to junction qi. You can print the roads in any order. If there are several solutions to that problem, print any of them.
Examples
Input
6 8
1 2
2 3
1 3
4 5
4 6
5 6
2 4
3 5
Output
1 2
2 3
3 1
4 5
5 6
6 4
4 2
3 5
Input
6 7
1 2
2 3
1 3
4 5
4 6
5 6
2 4
Output
0 | instruction | 0 | 41,304 | 1 | 82,608 |
Tags: dfs and similar, graphs
Correct Solution:
```
from collections import defaultdict
import os
import sys
from io import BytesIO, IOBase
from types import GeneratorType
from collections import defaultdict
BUFSIZE = 8192
class FastIO(IOBase):
newlines = 0
def __init__(self, file):
self._fd = file.fileno()
self.buffer = BytesIO()
self.writable = "x" in file.mode or "r" not in file.mode
self.write = self.buffer.write if self.writable else None
def read(self):
while True:
b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
if not b:
break
ptr = self.buffer.tell()
self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr)
self.newlines = 0
return self.buffer.read()
def readline(self):
while self.newlines == 0:
b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
self.newlines = b.count(b"\n") + (not b)
ptr = self.buffer.tell()
self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr)
self.newlines -= 1
return self.buffer.readline()
def flush(self):
if self.writable:
os.write(self._fd, self.buffer.getvalue())
self.buffer.truncate(0), self.buffer.seek(0)
class IOWrapper(IOBase):
def __init__(self, file):
self.buffer = FastIO(file)
self.flush = self.buffer.flush
self.writable = self.buffer.writable
self.write = lambda s: self.buffer.write(s.encode("ascii"))
self.read = lambda: self.buffer.read().decode("ascii")
self.readline = lambda: self.buffer.readline().decode("ascii")
sys.stdin, sys.stdout = IOWrapper(sys.stdin), IOWrapper(sys.stdout)
input = lambda: sys.stdin.readline().rstrip("\r\n")
sys.setrecursionlimit(3*10**4)
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,p):
for j in adj[u]:
if j!=p:
if id[j]==0:
id[j]=id[u]+1
yield dfs(j,u)
elif id[u]>id[j]:
up[u]+=1
down[j]+=1
yield
@bootstrap
def dfs2(u,p):
val[u]=up[u]-down[u]
for j in adj[u]:
if j!=p:
if id[j]==0:
id[j]=id[u]+1
ans.append([u, j])
yield dfs2(j,u)
val[u]+=val[j]
elif id[u]>id[j]:
ans.append([u, j])
yield
n,m=map(int,input().split())
adj=[[] for i in range(n+1)]
edges=[]
for j in range(m):
u,v=map(int,input().split())
adj[u].append(v)
adj[v].append(u)
up=defaultdict(lambda:0)
down=defaultdict(lambda:0)
id=[0]*(n+1)
id[1]=1
dfs(1,0)
val=[0]*(n+1)
id=[0]*(n+1)
id[1]=1
ans=[]
dfs2(1,0)
poss=1
for j in range(2,n+1):
if val[j]==0:
poss=0
break
if not poss:
print(0)
else:
for j in ans:
print(*j)
``` | output | 1 | 41,304 | 1 | 82,609 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Bertown has n junctions and m bidirectional roads. We know that one can get from any junction to any other one by the existing roads.
As there were more and more cars in the city, traffic jams started to pose real problems. To deal with them the government decided to make the traffic one-directional on all the roads, thus easing down the traffic. Your task is to determine whether there is a way to make the traffic one-directional so that there still is the possibility to get from any junction to any other one. If the answer is positive, you should also find one of the possible ways to orient the roads.
Input
The first line contains two space-separated integers n and m (2 ≤ n ≤ 105, n - 1 ≤ m ≤ 3·105) which represent the number of junctions and the roads in the town correspondingly. Then follow m lines, each containing two numbers which describe the roads in the city. Each road is determined by two integers ai and bi (1 ≤ ai, bi ≤ n, ai ≠ bi) — the numbers of junctions it connects.
It is guaranteed that one can get from any junction to any other one along the existing bidirectional roads. Each road connects different junctions, there is no more than one road between each pair of junctions.
Output
If there's no solution, print the single number 0. Otherwise, print m lines each containing two integers pi and qi — each road's orientation. That is the traffic flow will move along a one-directional road from junction pi to junction qi. You can print the roads in any order. If there are several solutions to that problem, print any of them.
Examples
Input
6 8
1 2
2 3
1 3
4 5
4 6
5 6
2 4
3 5
Output
1 2
2 3
3 1
4 5
5 6
6 4
4 2
3 5
Input
6 7
1 2
2 3
1 3
4 5
4 6
5 6
2 4
Output
0 | instruction | 0 | 41,305 | 1 | 82,610 |
Tags: dfs and similar, graphs
Correct Solution:
```
from sys import setrecursionlimit
from collections import defaultdict
from threading import stack_size,Thread
setrecursionlimit(1<<30)
stack_size(2**25)
edge=defaultdict(list)
visited=[False]*(100001)
intime=[0]*(100001)
low=[0]*(100001)
l1=[]
bridge=False
timer=0
def DFS(node,parent):
global l1,edge,visited,intime,low,timer,bridge
visited[node]=1
intime[node]=timer
low[node]=timer
timer+=1
for child in edge[node]:
if visited[child]==1:
if child==parent:
pass
else:
low[node]=min(intime[child],low[node])
if (intime[node]>intime[child]):
l1.append([node,child])
else:
DFS(child,node)
if low[child]>intime[node]:
bridge=True
return None
l1.append([node,child])
low[node]=min(low[node],low[child])
def main():
r=lambda:map(int,input().split())
n,m=r()
global edge,visited,intime,low,l1,bridge,timer
for i in range(1,n+1):
edge[i]=[]
visited[i]=0
intime[i]=0
low[i]=0
for _ in range(m):
p,q=r()
edge[p].append(q)
edge[q].append(p)
DFS(1,-1)
if bridge==True:
print(0)
else:
# print(l1)
for i in l1:
print(*i)
if __name__ == "__main__":
Thread(target=main).start()
``` | output | 1 | 41,305 | 1 | 82,611 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Bertown has n junctions and m bidirectional roads. We know that one can get from any junction to any other one by the existing roads.
As there were more and more cars in the city, traffic jams started to pose real problems. To deal with them the government decided to make the traffic one-directional on all the roads, thus easing down the traffic. Your task is to determine whether there is a way to make the traffic one-directional so that there still is the possibility to get from any junction to any other one. If the answer is positive, you should also find one of the possible ways to orient the roads.
Input
The first line contains two space-separated integers n and m (2 ≤ n ≤ 105, n - 1 ≤ m ≤ 3·105) which represent the number of junctions and the roads in the town correspondingly. Then follow m lines, each containing two numbers which describe the roads in the city. Each road is determined by two integers ai and bi (1 ≤ ai, bi ≤ n, ai ≠ bi) — the numbers of junctions it connects.
It is guaranteed that one can get from any junction to any other one along the existing bidirectional roads. Each road connects different junctions, there is no more than one road between each pair of junctions.
Output
If there's no solution, print the single number 0. Otherwise, print m lines each containing two integers pi and qi — each road's orientation. That is the traffic flow will move along a one-directional road from junction pi to junction qi. You can print the roads in any order. If there are several solutions to that problem, print any of them.
Examples
Input
6 8
1 2
2 3
1 3
4 5
4 6
5 6
2 4
3 5
Output
1 2
2 3
3 1
4 5
5 6
6 4
4 2
3 5
Input
6 7
1 2
2 3
1 3
4 5
4 6
5 6
2 4
Output
0 | instruction | 0 | 41,306 | 1 | 82,612 |
Tags: dfs and similar, graphs
Correct Solution:
```
import os
from io import BytesIO, IOBase
import sys
sys.setrecursionlimit(10**6)
import threading
threading.stack_size(2**25)
vis=[0]*(10**5+1)
low=[0]*(10**5+1)
timer=0
ans=0
d={1:[] for i in range(10**6+1)}
intim=[0]*(10**6+1)
arr=[]
def dfs(child,par):
global timer,ans,vis,low,d,arr,intim
vis[child]=1
low[child]=intim[child]=timer
timer+=1
for i in d[child]:
if i==par:
continue
if vis[i]:
low[child]=min(low[child],intim[i])
if intim[child]>intim[i]:
arr.append([child,i])
else:
dfs(i,child)
if low[i]>intim[child]:
ans=1
return
arr.append([child,i])
low[child]=min(low[child],low[i])
def main():
n, m = map(int, input().split())
global vis, low, timer, d, intim, arr, ans
d = {i: [] for i in range(n + 1)}
for _ in range(m):
a, b = map(int, input().split())
d[a].append(b)
d[b].append(a)
ans = 0
arr = []
vis = [0] * (n + 1)
low = [0] * (n + 1)
timer = 0
intim = [0] * (n + 1)
dfs(1, -1)
if ans == 1:
print(0)
else:
for i in arr:
print(i[0], i[1])
# 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())
threading.Thread(target=main).start()
``` | output | 1 | 41,306 | 1 | 82,613 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Bertown has n junctions and m bidirectional roads. We know that one can get from any junction to any other one by the existing roads.
As there were more and more cars in the city, traffic jams started to pose real problems. To deal with them the government decided to make the traffic one-directional on all the roads, thus easing down the traffic. Your task is to determine whether there is a way to make the traffic one-directional so that there still is the possibility to get from any junction to any other one. If the answer is positive, you should also find one of the possible ways to orient the roads.
Input
The first line contains two space-separated integers n and m (2 ≤ n ≤ 105, n - 1 ≤ m ≤ 3·105) which represent the number of junctions and the roads in the town correspondingly. Then follow m lines, each containing two numbers which describe the roads in the city. Each road is determined by two integers ai and bi (1 ≤ ai, bi ≤ n, ai ≠ bi) — the numbers of junctions it connects.
It is guaranteed that one can get from any junction to any other one along the existing bidirectional roads. Each road connects different junctions, there is no more than one road between each pair of junctions.
Output
If there's no solution, print the single number 0. Otherwise, print m lines each containing two integers pi and qi — each road's orientation. That is the traffic flow will move along a one-directional road from junction pi to junction qi. You can print the roads in any order. If there are several solutions to that problem, print any of them.
Examples
Input
6 8
1 2
2 3
1 3
4 5
4 6
5 6
2 4
3 5
Output
1 2
2 3
3 1
4 5
5 6
6 4
4 2
3 5
Input
6 7
1 2
2 3
1 3
4 5
4 6
5 6
2 4
Output
0 | instruction | 0 | 41,307 | 1 | 82,614 |
Tags: dfs and similar, graphs
Correct Solution:
```
import sys
from threading import stack_size,Thread
sys.setrecursionlimit(10**6)
stack_size(2**25)
def inputt():
return sys.stdin.readline().strip()
timer=0
g=False
dic={}
visited={}
in_time=[]
low=[]
edges=[]
def dfs(node,parent):
global timer
visited[node]=1
in_time[node]=low[node]=timer
timer+=1
for i in dic[node]:
if i==parent:
# if cur node's child is parent than for forward edge it is valid ancestor
continue
# even after checking for parent it is already visited than it is a back edge
if visited[i]==1:
# This is a back edge
# So we are updating the lowtime of cur node with intime of
low[node]=min(low[node],in_time[i])
if in_time[node]>in_time[i]:
edges.append((node,i))
else:
dfs(i,node)
# if low[child]<in[node]
# even if you remove this edge child is still connected from another path. so can't be a bridge
if low[i]>in_time[node]:
global g
g=True
return
#print(node,i,"bridge")
edges.append((node,i))
low[node]=min(low[node],low[i])
def main() :
for _ in range(1):
n,m=map(int,inputt().split())
global dic
for i in range(m):
u,v=map(int,inputt().split())
if u in dic:
dic[u].append(v)
else:
dic[u]=[v]
if v in dic:
dic[v].append(u)
else:
dic[v]=[u]
global visited,in_time,low,edges
in_time=[0]*(n+1)
low=[0]*(n+1)
for i in range(1,n+1):
visited[i]=0
dfs(1,-1)
if g:
print(0)
else:
for i,j in edges:
print(i,j)
Thread(target=main).start()
``` | output | 1 | 41,307 | 1 | 82,615 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Bertown has n junctions and m bidirectional roads. We know that one can get from any junction to any other one by the existing roads.
As there were more and more cars in the city, traffic jams started to pose real problems. To deal with them the government decided to make the traffic one-directional on all the roads, thus easing down the traffic. Your task is to determine whether there is a way to make the traffic one-directional so that there still is the possibility to get from any junction to any other one. If the answer is positive, you should also find one of the possible ways to orient the roads.
Input
The first line contains two space-separated integers n and m (2 ≤ n ≤ 105, n - 1 ≤ m ≤ 3·105) which represent the number of junctions and the roads in the town correspondingly. Then follow m lines, each containing two numbers which describe the roads in the city. Each road is determined by two integers ai and bi (1 ≤ ai, bi ≤ n, ai ≠ bi) — the numbers of junctions it connects.
It is guaranteed that one can get from any junction to any other one along the existing bidirectional roads. Each road connects different junctions, there is no more than one road between each pair of junctions.
Output
If there's no solution, print the single number 0. Otherwise, print m lines each containing two integers pi and qi — each road's orientation. That is the traffic flow will move along a one-directional road from junction pi to junction qi. You can print the roads in any order. If there are several solutions to that problem, print any of them.
Examples
Input
6 8
1 2
2 3
1 3
4 5
4 6
5 6
2 4
3 5
Output
1 2
2 3
3 1
4 5
5 6
6 4
4 2
3 5
Input
6 7
1 2
2 3
1 3
4 5
4 6
5 6
2 4
Output
0 | instruction | 0 | 41,308 | 1 | 82,616 |
Tags: dfs and similar, graphs
Correct Solution:
```
from sys import stdin,stdout,setrecursionlimit
from collections import defaultdict,deque
from threading import stack_size,Thread
setrecursionlimit(10**6)
stack_size(2**25)
graph=defaultdict(list)
bridge=False
vis=[0]*(100001)
low=[0]*(100001)
In=[0]*(100001)
timer=0
ans=[]
def dfs(v,par):
global graph, vis, In, low, ans, bridge,timer
vis[v]=1
In[v]=timer
low[v]=timer
timer+=1
if bridge == True:
return None
for i in graph[v]:
if i==par:
continue
if vis[i]==1:
low[v]=min(low[v],In[i])
if In[v]>In[i]:
ans.append([v,i])
else:
dfs(i,v)
if low[i]>In[v]:
bridge=True
return None
ans.append([v,i])
low[v]=min(low[v],low[i])
def solve():
n,m=map(int,stdin.readline().split())
global graph, vis, In, low, ans, bridge,timer
timer=0
bridge=False
for i in range(m):
a,b=map(int,stdin.readline().split())
graph[a].append(b)
graph[b].append(a)
dfs(1,-1)
if bridge:
print(0)
else:
for i in range(len(ans)):
print(*ans[i])
if __name__=='__main__':
Thread(target=solve).start()
``` | output | 1 | 41,308 | 1 | 82,617 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Bertown has n junctions and m bidirectional roads. We know that one can get from any junction to any other one by the existing roads.
As there were more and more cars in the city, traffic jams started to pose real problems. To deal with them the government decided to make the traffic one-directional on all the roads, thus easing down the traffic. Your task is to determine whether there is a way to make the traffic one-directional so that there still is the possibility to get from any junction to any other one. If the answer is positive, you should also find one of the possible ways to orient the roads.
Input
The first line contains two space-separated integers n and m (2 ≤ n ≤ 105, n - 1 ≤ m ≤ 3·105) which represent the number of junctions and the roads in the town correspondingly. Then follow m lines, each containing two numbers which describe the roads in the city. Each road is determined by two integers ai and bi (1 ≤ ai, bi ≤ n, ai ≠ bi) — the numbers of junctions it connects.
It is guaranteed that one can get from any junction to any other one along the existing bidirectional roads. Each road connects different junctions, there is no more than one road between each pair of junctions.
Output
If there's no solution, print the single number 0. Otherwise, print m lines each containing two integers pi and qi — each road's orientation. That is the traffic flow will move along a one-directional road from junction pi to junction qi. You can print the roads in any order. If there are several solutions to that problem, print any of them.
Examples
Input
6 8
1 2
2 3
1 3
4 5
4 6
5 6
2 4
3 5
Output
1 2
2 3
3 1
4 5
5 6
6 4
4 2
3 5
Input
6 7
1 2
2 3
1 3
4 5
4 6
5 6
2 4
Output
0
Submitted Solution:
```
from bisect import bisect
from heapq import heappush as hpush,heappop as hpop
from sys import stdin,setrecursionlimit
import threading
input = lambda: stdin.readline().rstrip("\r\n")
from collections import deque as que
inin = lambda: int(input())
inar = lambda: list(map(int,input().split()))
from collections import defaultdict
adj=defaultdict(list)
visited=[False]*(100001)
intime=[0]*(100001)
outtime=[0]*(100001)
res=[]
bridge=False
timer=0
def dfs(root,p):
global adj, visited, intime, outtime, res, bridge,timer
visited[root]=True
intime[root]=timer
outtime[root]=timer
first=[0]*(100001)
timer+=1
bridge=False
stack = [(root, p, adj[root].__iter__())]
while stack:
node,par,i = stack.pop()
try:
j = next(i)
stack.append((node,par,i))
if not visited[node]: #since in our algorithm we are again pushing visited node into stack
visited[node]=True #we need to first check if the popped node was visited as we may have previsit opoerations
intime[node]=outtime[node]=timer
timer+=1
#previsit (node,parent)
if j==par:
continue
if visited[j]:
outtime[node]=min(outtime[node],intime[j])
if intime[node]>intime[j]:
res.append((node,j))
else:
stack.append((j,node,adj[j].__iter__()))
except StopIteration:
if node==root:
#postvisit of root
continue
#postvisit (node,par)
if outtime[node]>intime[par]:
bridge=True
return
res.append((par,node))
outtime[par]=min(outtime[par],outtime[node])
def main():
n,m=map(int,input().split())
global adj,visited,intime,outtime,res,bridge,timer
timer=0
bridge=False
for i in range(m):
u,v=map(int,input().split())
adj[u].append(v)
adj[v].append(u)
dfs(1,-1)
if bridge:
print(0)
else:
for i in range(len(res)):
print(*res[i])
main()
``` | instruction | 0 | 41,309 | 1 | 82,618 |
Yes | output | 1 | 41,309 | 1 | 82,619 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Bertown has n junctions and m bidirectional roads. We know that one can get from any junction to any other one by the existing roads.
As there were more and more cars in the city, traffic jams started to pose real problems. To deal with them the government decided to make the traffic one-directional on all the roads, thus easing down the traffic. Your task is to determine whether there is a way to make the traffic one-directional so that there still is the possibility to get from any junction to any other one. If the answer is positive, you should also find one of the possible ways to orient the roads.
Input
The first line contains two space-separated integers n and m (2 ≤ n ≤ 105, n - 1 ≤ m ≤ 3·105) which represent the number of junctions and the roads in the town correspondingly. Then follow m lines, each containing two numbers which describe the roads in the city. Each road is determined by two integers ai and bi (1 ≤ ai, bi ≤ n, ai ≠ bi) — the numbers of junctions it connects.
It is guaranteed that one can get from any junction to any other one along the existing bidirectional roads. Each road connects different junctions, there is no more than one road between each pair of junctions.
Output
If there's no solution, print the single number 0. Otherwise, print m lines each containing two integers pi and qi — each road's orientation. That is the traffic flow will move along a one-directional road from junction pi to junction qi. You can print the roads in any order. If there are several solutions to that problem, print any of them.
Examples
Input
6 8
1 2
2 3
1 3
4 5
4 6
5 6
2 4
3 5
Output
1 2
2 3
3 1
4 5
5 6
6 4
4 2
3 5
Input
6 7
1 2
2 3
1 3
4 5
4 6
5 6
2 4
Output
0
Submitted Solution:
```
# by the authority of GOD author: manhar singh sachdev #
import os,sys
from io import BytesIO, IOBase
def bridges(n,path):
poi,start,low,st,time = [0]*n,[0]*n,[10**10]*n,[0],0
visi,edg = [1]+[0]*(n-1),[]
while len(st):
x,y = st[-1],path[st[-1]]
while poi[x] != len(y) and visi[y[poi[x]]]:
if len(st) > 1 and y[poi[x]] != st[-2]:
low[x] = min(low[x],start[y[poi[x]]])
if start[y[poi[x]]] < start[x]:
edg.append((x+1,y[poi[x]]+1))
poi[x] += 1
if poi[x] == len(y):
zz = st.pop()
if len(st):
low[st[-1]] = min(low[st[-1]],low[zz])
if low[zz] > start[st[-1]]:
return []
else:
time += 1
i = y[poi[x]]
visi[i] = 1
st.append(i)
start[i] = time
poi[x] += 1
edg.append((x+1,i+1))
return edg
def main():
n,m = map(int,input().split())
path = [[] for _ in range(n)]
for _ in range(m):
u1,v1 = map(lambda xx:int(xx)-1,input().split())
path[u1].append(v1)
path[v1].append(u1)
x = bridges(n,path)
if not len(x):
print(0)
else:
for i in x:
print(*i)
# 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()
``` | instruction | 0 | 41,310 | 1 | 82,620 |
Yes | output | 1 | 41,310 | 1 | 82,621 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Bertown has n junctions and m bidirectional roads. We know that one can get from any junction to any other one by the existing roads.
As there were more and more cars in the city, traffic jams started to pose real problems. To deal with them the government decided to make the traffic one-directional on all the roads, thus easing down the traffic. Your task is to determine whether there is a way to make the traffic one-directional so that there still is the possibility to get from any junction to any other one. If the answer is positive, you should also find one of the possible ways to orient the roads.
Input
The first line contains two space-separated integers n and m (2 ≤ n ≤ 105, n - 1 ≤ m ≤ 3·105) which represent the number of junctions and the roads in the town correspondingly. Then follow m lines, each containing two numbers which describe the roads in the city. Each road is determined by two integers ai and bi (1 ≤ ai, bi ≤ n, ai ≠ bi) — the numbers of junctions it connects.
It is guaranteed that one can get from any junction to any other one along the existing bidirectional roads. Each road connects different junctions, there is no more than one road between each pair of junctions.
Output
If there's no solution, print the single number 0. Otherwise, print m lines each containing two integers pi and qi — each road's orientation. That is the traffic flow will move along a one-directional road from junction pi to junction qi. You can print the roads in any order. If there are several solutions to that problem, print any of them.
Examples
Input
6 8
1 2
2 3
1 3
4 5
4 6
5 6
2 4
3 5
Output
1 2
2 3
3 1
4 5
5 6
6 4
4 2
3 5
Input
6 7
1 2
2 3
1 3
4 5
4 6
5 6
2 4
Output
0
Submitted Solution:
```
from bisect import bisect
from heapq import heappush as hpush,heappop as hpop
from sys import stdin,setrecursionlimit
import threading
input = lambda: stdin.readline().rstrip("\r\n")
from collections import deque as que
inin = lambda: int(input())
inar = lambda: list(map(int,input().split()))
from collections import defaultdict
adj=defaultdict(list)
visited=[False]*(100001)
intime=[0]*(100001)
outtime=[0]*(100001)
res=[]
bridge=False
timer=0
def dfs(root,p):
global adj, visited, intime, outtime, res, bridge,timer
visited[root]=True
intime[root]=timer
outtime[root]=timer
first=[0]*(100001)
timer+=1
bridge=False
stack = [(root, p, adj[root].__iter__())]
while stack:
try:
node,par,i = stack.pop()
#print('stack= ',node,par,i)
j = next(i)
stack.append((node,par,i))
#previsit (node,parent)
if not visited[node]:
visited[node]=True
intime[node]=outtime[node]=timer
timer+=1
if j==par:
continue
if visited[j]:
outtime[node]=min(outtime[node],intime[j])
if intime[node]>intime[j]:
res.append((node,j))
else:
stack.append((j,node,adj[j].__iter__()))
except StopIteration:
#postvisit (node,par)
if node==root:
continue
if outtime[node]>intime[par]:
#print('postvisit ',node,par)
bridge=True
return
res.append((par,node))
outtime[par]=min(outtime[par],outtime[node])
def main():
n,m=map(int,input().split())
global adj,visited,intime,outtime,res,bridge,timer
timer=0
bridge=False
for i in range(m):
u,v=map(int,input().split())
adj[u].append(v)
adj[v].append(u)
dfs(1,-1)
if bridge:
print(0)
else:
for i in range(len(res)):
print(*res[i])
main()
``` | instruction | 0 | 41,311 | 1 | 82,622 |
Yes | output | 1 | 41,311 | 1 | 82,623 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Bertown has n junctions and m bidirectional roads. We know that one can get from any junction to any other one by the existing roads.
As there were more and more cars in the city, traffic jams started to pose real problems. To deal with them the government decided to make the traffic one-directional on all the roads, thus easing down the traffic. Your task is to determine whether there is a way to make the traffic one-directional so that there still is the possibility to get from any junction to any other one. If the answer is positive, you should also find one of the possible ways to orient the roads.
Input
The first line contains two space-separated integers n and m (2 ≤ n ≤ 105, n - 1 ≤ m ≤ 3·105) which represent the number of junctions and the roads in the town correspondingly. Then follow m lines, each containing two numbers which describe the roads in the city. Each road is determined by two integers ai and bi (1 ≤ ai, bi ≤ n, ai ≠ bi) — the numbers of junctions it connects.
It is guaranteed that one can get from any junction to any other one along the existing bidirectional roads. Each road connects different junctions, there is no more than one road between each pair of junctions.
Output
If there's no solution, print the single number 0. Otherwise, print m lines each containing two integers pi and qi — each road's orientation. That is the traffic flow will move along a one-directional road from junction pi to junction qi. You can print the roads in any order. If there are several solutions to that problem, print any of them.
Examples
Input
6 8
1 2
2 3
1 3
4 5
4 6
5 6
2 4
3 5
Output
1 2
2 3
3 1
4 5
5 6
6 4
4 2
3 5
Input
6 7
1 2
2 3
1 3
4 5
4 6
5 6
2 4
Output
0
Submitted Solution:
```
from sys import stdin,stdout,setrecursionlimit
from collections import defaultdict
from threading import stack_size,Thread
setrecursionlimit(10**6)
stack_size(2**25)
edge=defaultdict(list)
bridge=False
vis=[0]*(100001)
low=[0]*(100001)
inTime=[0]*(100001)
timer=0
ans=[]
def dfs(node,parent):
global edge, vis, inTime, low, ans, bridge,timer
vis[node]=1
low[node]=timer
inTime[node]=timer
timer+=1
for j in edge[node]:
if j==parent:
continue
if vis[j]==1:
low[node]=min(low[node],inTime[j])
if inTime[node]>inTime[j]:
ans.append([node,j])
else:
dfs(j,node)
if low[j]>inTime[node]:
bridge=True
return
ans.append([node,j])
low[node]=min(low[node],low[j])
def solve():
n,m=map(int,stdin.readline().split())
global edge, vis, inTime, low, ans, bridge,timer
timer=0
bridge=False
for i in range(m):
u,v=map(int,stdin.readline().split())
edge[u].append(v)
edge[v].append(u)
dfs(1,-1)
if bridge:
print(0)
else:
for i in range(len(ans)):
print(*ans[i])
if __name__=='__main__':
Thread(target=solve).start()
``` | instruction | 0 | 41,312 | 1 | 82,624 |
Yes | output | 1 | 41,312 | 1 | 82,625 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Bertown has n junctions and m bidirectional roads. We know that one can get from any junction to any other one by the existing roads.
As there were more and more cars in the city, traffic jams started to pose real problems. To deal with them the government decided to make the traffic one-directional on all the roads, thus easing down the traffic. Your task is to determine whether there is a way to make the traffic one-directional so that there still is the possibility to get from any junction to any other one. If the answer is positive, you should also find one of the possible ways to orient the roads.
Input
The first line contains two space-separated integers n and m (2 ≤ n ≤ 105, n - 1 ≤ m ≤ 3·105) which represent the number of junctions and the roads in the town correspondingly. Then follow m lines, each containing two numbers which describe the roads in the city. Each road is determined by two integers ai and bi (1 ≤ ai, bi ≤ n, ai ≠ bi) — the numbers of junctions it connects.
It is guaranteed that one can get from any junction to any other one along the existing bidirectional roads. Each road connects different junctions, there is no more than one road between each pair of junctions.
Output
If there's no solution, print the single number 0. Otherwise, print m lines each containing two integers pi and qi — each road's orientation. That is the traffic flow will move along a one-directional road from junction pi to junction qi. You can print the roads in any order. If there are several solutions to that problem, print any of them.
Examples
Input
6 8
1 2
2 3
1 3
4 5
4 6
5 6
2 4
3 5
Output
1 2
2 3
3 1
4 5
5 6
6 4
4 2
3 5
Input
6 7
1 2
2 3
1 3
4 5
4 6
5 6
2 4
Output
0
Submitted Solution:
```
from sys import setrecursionlimit
setrecursionlimit(1000000)
totalvisited=0
pi = []
def dfs_visit(G,u,sol):
global totalvisited
totalvisited+=1
color[u] = 1
for v in G[u]:
if color[v] == 0 :
pi[v] = u
sol.append((u,v))
dfs_visit(G,v,sol)
elif pi[u]!=v:
if color[v] == 1:
sol.append((u,v))
color[u] =2
def init(n):
global pi,color,totalvisited
pi=[0 for i in range(n) ]
pi[0] = -1
color = [ 0 for i in range(n)]
totalvisited = 0
def main():
s = input().split(" ")
n = int(s[0])
m = int(s[1])
G=[ [] for i in range(n) ]
for _ in range(m):
s =input().split(" ")
n1 = int(s[0])-1
n2 = int(s[1])-1
G[n2].append(n1)
G[n1].append(n2)
init(n)
sol = []
dfs_visit(G,0,sol)
G2=[ [] for i in range(n) ]
for x,y in sol:
G2[y].append(x)
init(n)
dfs_visit(G2,0,[])
if totalvisited!=n:
print(0)
return
for x,y in sol:
print(x+1,y+1)
try:
main()
except Exception as e:
print(str(e).replace(" ","_"))
``` | instruction | 0 | 41,313 | 1 | 82,626 |
No | output | 1 | 41,313 | 1 | 82,627 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Bertown has n junctions and m bidirectional roads. We know that one can get from any junction to any other one by the existing roads.
As there were more and more cars in the city, traffic jams started to pose real problems. To deal with them the government decided to make the traffic one-directional on all the roads, thus easing down the traffic. Your task is to determine whether there is a way to make the traffic one-directional so that there still is the possibility to get from any junction to any other one. If the answer is positive, you should also find one of the possible ways to orient the roads.
Input
The first line contains two space-separated integers n and m (2 ≤ n ≤ 105, n - 1 ≤ m ≤ 3·105) which represent the number of junctions and the roads in the town correspondingly. Then follow m lines, each containing two numbers which describe the roads in the city. Each road is determined by two integers ai and bi (1 ≤ ai, bi ≤ n, ai ≠ bi) — the numbers of junctions it connects.
It is guaranteed that one can get from any junction to any other one along the existing bidirectional roads. Each road connects different junctions, there is no more than one road between each pair of junctions.
Output
If there's no solution, print the single number 0. Otherwise, print m lines each containing two integers pi and qi — each road's orientation. That is the traffic flow will move along a one-directional road from junction pi to junction qi. You can print the roads in any order. If there are several solutions to that problem, print any of them.
Examples
Input
6 8
1 2
2 3
1 3
4 5
4 6
5 6
2 4
3 5
Output
1 2
2 3
3 1
4 5
5 6
6 4
4 2
3 5
Input
6 7
1 2
2 3
1 3
4 5
4 6
5 6
2 4
Output
0
Submitted Solution:
```
d = []
pi = []
low = []
time = 0
def dfs_visit_bridges(G,u):
global time
color[u] = 1
time +=1
d[u] = time
low[u] = time
for v in G[u]:
if color[v] == 0 :
pi[v] = u
if dfs_visit_bridges(G,v):
return True
low[u] = min(low[v], low[u])
elif pi[u]!=v:
low[u] = min(low[u] , d[v])
if low[u] == d[u] and u!=0:
return True
color[u] =2
time+=1
return False
def dfs_visit(G,u,sol):
color[u] = 1
for v in G[u]:
if color[v] == 0 :
pi[v] = u
sol.append((u,v))
dfs_visit(G,v,sol)
elif pi[u]!=v:
if color[v] == 1:
sol.append((u,v))
color[u] =2
def dfs(G):
sol=[]
dfs_visit(G,0,sol)
return sol
def init(n):
global d,pi, color,low,time
low=[0 for i in range(n) ]
d=[0 for i in range(n) ]
pi=[0 for i in range(n) ]
pi[0] = -1
color = [ 0 for i in range(n)]
time = 0
def main():
s = input().split(" ")
n = int(s[0])
m = int(s[1])
G=[ [] for i in range(n) ]
for _ in range(m):
s =input().split(" ")
n1 = int(s[0])-1
n2 = int(s[1])-1
G[n2].append(n1)
G[n1].append(n2)
# n=1000 and m= 132510
init(n)
if dfs_visit_bridges(G,0):
print(0)
else:
init(n)
sol = dfs(G)
for x,y in sol:
print(x+1,y+1)
try:
main()
except Exception as e:
print(str(e).replace(" ","_"))
``` | instruction | 0 | 41,314 | 1 | 82,628 |
No | output | 1 | 41,314 | 1 | 82,629 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Bertown has n junctions and m bidirectional roads. We know that one can get from any junction to any other one by the existing roads.
As there were more and more cars in the city, traffic jams started to pose real problems. To deal with them the government decided to make the traffic one-directional on all the roads, thus easing down the traffic. Your task is to determine whether there is a way to make the traffic one-directional so that there still is the possibility to get from any junction to any other one. If the answer is positive, you should also find one of the possible ways to orient the roads.
Input
The first line contains two space-separated integers n and m (2 ≤ n ≤ 105, n - 1 ≤ m ≤ 3·105) which represent the number of junctions and the roads in the town correspondingly. Then follow m lines, each containing two numbers which describe the roads in the city. Each road is determined by two integers ai and bi (1 ≤ ai, bi ≤ n, ai ≠ bi) — the numbers of junctions it connects.
It is guaranteed that one can get from any junction to any other one along the existing bidirectional roads. Each road connects different junctions, there is no more than one road between each pair of junctions.
Output
If there's no solution, print the single number 0. Otherwise, print m lines each containing two integers pi and qi — each road's orientation. That is the traffic flow will move along a one-directional road from junction pi to junction qi. You can print the roads in any order. If there are several solutions to that problem, print any of them.
Examples
Input
6 8
1 2
2 3
1 3
4 5
4 6
5 6
2 4
3 5
Output
1 2
2 3
3 1
4 5
5 6
6 4
4 2
3 5
Input
6 7
1 2
2 3
1 3
4 5
4 6
5 6
2 4
Output
0
Submitted Solution:
```
I=lambda:list(map(int,input().split()))
n,m=I()
g=[[] for i in range(n)]
for q in range(m):
x,y=I()
x-=1;y-=1
g[x].append(y);g[y].append(x)
ans=[]
st=[0]
visi=[0]*n
tin=[0]*n
low=[0]*n
ans=[]
flag=1
def dfs(u,p,t):
t+=1
tin[u]=low[u]=t
visi[u]=1
for v in g[u]:
if v==p:
continue
if visi[v]:
low[u]=min(low[u],tin[v])
ans.append([v+1,u+1])
else:
ans.append([u+1,v+1])
dfs(v,u,t)
low[u]=min(low[u],low[v])
if low[v]>tin[u]:
global flag
flag=0
dfs(0,-1,0)
if flag:
for i in ans:
print(*i)
else:
print(0)
``` | instruction | 0 | 41,315 | 1 | 82,630 |
No | output | 1 | 41,315 | 1 | 82,631 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Bertown has n junctions and m bidirectional roads. We know that one can get from any junction to any other one by the existing roads.
As there were more and more cars in the city, traffic jams started to pose real problems. To deal with them the government decided to make the traffic one-directional on all the roads, thus easing down the traffic. Your task is to determine whether there is a way to make the traffic one-directional so that there still is the possibility to get from any junction to any other one. If the answer is positive, you should also find one of the possible ways to orient the roads.
Input
The first line contains two space-separated integers n and m (2 ≤ n ≤ 105, n - 1 ≤ m ≤ 3·105) which represent the number of junctions and the roads in the town correspondingly. Then follow m lines, each containing two numbers which describe the roads in the city. Each road is determined by two integers ai and bi (1 ≤ ai, bi ≤ n, ai ≠ bi) — the numbers of junctions it connects.
It is guaranteed that one can get from any junction to any other one along the existing bidirectional roads. Each road connects different junctions, there is no more than one road between each pair of junctions.
Output
If there's no solution, print the single number 0. Otherwise, print m lines each containing two integers pi and qi — each road's orientation. That is the traffic flow will move along a one-directional road from junction pi to junction qi. You can print the roads in any order. If there are several solutions to that problem, print any of them.
Examples
Input
6 8
1 2
2 3
1 3
4 5
4 6
5 6
2 4
3 5
Output
1 2
2 3
3 1
4 5
5 6
6 4
4 2
3 5
Input
6 7
1 2
2 3
1 3
4 5
4 6
5 6
2 4
Output
0
Submitted Solution:
```
d = []
pi = []
low = []
time = 0
def dfs_visit_bridges(G,u):
global time
color[u] = 1
time +=1
d[u] = time
low[u] = time
for v in G[u]:
if color[v] == 0 :
pi[v] = u
if dfs_visit_bridges(G,v):
return True
low[u] = min(low[v], low[u])
elif pi[u]!=v:
low[u] = min(low[u] , d[v])
if low[u] == d[u] and u!=0:
return True
color[u] =2
time+=1
return False
def dfs_visit(G,u,sol):
color[u] = 1
for v in G[u]:
if color[v] == 0 :
pi[v] = u
sol.append((u,v))
dfs_visit(G,v,sol)
elif pi[u]!=v:
if color[v] == 1:
sol.append((u,v))
color[u] =2
def dfs(G):
sol=[]
dfs_visit(G,0,sol)
return sol
def init(n):
global d,pi, color,low,time
low=[0 for i in range(n) ]
d=[0 for i in range(n) ]
pi=[0 for i in range(n) ]
pi[0] = -1
color = [ 0 for i in range(n)]
time = 0
def main():
s = input().split(" ")
n = int(s[0])
m = int(s[1])
G=[ [] for i in range(n) ]
for _ in range(m):
s =input().split(" ")
n1 = int(s[0])-1
n2 = int(s[1])-1
G[n2].append(n1)
G[n1].append(n2)
# n=1000 and m= 132510
init(n)
if dfs_visit_bridges(G,0):
print(0)
else:
init(n)
sol = dfs(G)
for x,y in sol:
print(x+1,y+1)
try:
main()
except Exception as e:
print("el error fue:",e)
``` | instruction | 0 | 41,316 | 1 | 82,632 |
No | output | 1 | 41,316 | 1 | 82,633 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Recently, Mike was very busy with studying for exams and contests. Now he is going to chill a bit by doing some sight seeing in the city.
City consists of n intersections numbered from 1 to n. Mike starts walking from his house located at the intersection number 1 and goes along some sequence of intersections. Walking from intersection number i to intersection j requires |i - j| units of energy. The total energy spent by Mike to visit a sequence of intersections p1 = 1, p2, ..., pk is equal to <image> units of energy.
Of course, walking would be boring if there were no shortcuts. A shortcut is a special path that allows Mike walking from one intersection to another requiring only 1 unit of energy. There are exactly n shortcuts in Mike's city, the ith of them allows walking from intersection i to intersection ai (i ≤ ai ≤ ai + 1) (but not in the opposite direction), thus there is exactly one shortcut starting at each intersection. Formally, if Mike chooses a sequence p1 = 1, p2, ..., pk then for each 1 ≤ i < k satisfying pi + 1 = api and api ≠ pi Mike will spend only 1 unit of energy instead of |pi - pi + 1| walking from the intersection pi to intersection pi + 1. For example, if Mike chooses a sequence p1 = 1, p2 = ap1, p3 = ap2, ..., pk = apk - 1, he spends exactly k - 1 units of total energy walking around them.
Before going on his adventure, Mike asks you to find the minimum amount of energy required to reach each of the intersections from his home. Formally, for each 1 ≤ i ≤ n Mike is interested in finding minimum possible total energy of some sequence p1 = 1, p2, ..., pk = i.
Input
The first line contains an integer n (1 ≤ n ≤ 200 000) — the number of Mike's city intersection.
The second line contains n integers a1, a2, ..., an (i ≤ ai ≤ n , <image>, describing shortcuts of Mike's city, allowing to walk from intersection i to intersection ai using only 1 unit of energy. Please note that the shortcuts don't allow walking in opposite directions (from ai to i).
Output
In the only line print n integers m1, m2, ..., mn, where mi denotes the least amount of total energy required to walk from intersection 1 to intersection i.
Examples
Input
3
2 2 3
Output
0 1 2
Input
5
1 2 3 4 5
Output
0 1 2 3 4
Input
7
4 4 4 4 7 7 7
Output
0 1 2 1 2 3 3
Note
In the first sample case desired sequences are:
1: 1; m1 = 0;
2: 1, 2; m2 = 1;
3: 1, 3; m3 = |3 - 1| = 2.
In the second sample case the sequence for any intersection 1 < i is always 1, i and mi = |1 - i|.
In the third sample case — consider the following intersection sequences:
1: 1; m1 = 0;
2: 1, 2; m2 = |2 - 1| = 1;
3: 1, 4, 3; m3 = 1 + |4 - 3| = 2;
4: 1, 4; m4 = 1;
5: 1, 4, 5; m5 = 1 + |4 - 5| = 2;
6: 1, 4, 6; m6 = 1 + |4 - 6| = 3;
7: 1, 4, 5, 7; m7 = 1 + |4 - 5| + 1 = 3. | instruction | 0 | 41,673 | 1 | 83,346 |
Tags: dfs and similar, graphs, greedy, shortest paths
Correct Solution:
```
from queue import Queue
def bfs(vertice):
q = Queue()
q.put(vertice)
dist[vertice] = 0
while not q.empty():
v = q.get()
# print('visitando %d' % vertice)
for vizinho in adj[v]:
if dist[vizinho] > dist[v] + 1:
dist[vizinho] = dist[v] + 1
q.put(vizinho)
# print(dist)
INF = 10 ** 9 # 10^9
n = int(input())
adj = [0]
adj.extend([int(x) for x in input().split()])
dist = [INF] * (n + 1)
# for i in range(n + 1):
# # adj.append([])
# dist.append(INF)
for i in range(1, n + 1):
adj[i] = [adj[i]]
if i != 1:
adj[i].append(i - 1)
if i != n:
adj[i].append(i + 1)
bfs(1)
result = ""
for i in range(1, len(dist)):
result += str(dist[i]) + " "
print(result)
``` | output | 1 | 41,673 | 1 | 83,347 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Recently, Mike was very busy with studying for exams and contests. Now he is going to chill a bit by doing some sight seeing in the city.
City consists of n intersections numbered from 1 to n. Mike starts walking from his house located at the intersection number 1 and goes along some sequence of intersections. Walking from intersection number i to intersection j requires |i - j| units of energy. The total energy spent by Mike to visit a sequence of intersections p1 = 1, p2, ..., pk is equal to <image> units of energy.
Of course, walking would be boring if there were no shortcuts. A shortcut is a special path that allows Mike walking from one intersection to another requiring only 1 unit of energy. There are exactly n shortcuts in Mike's city, the ith of them allows walking from intersection i to intersection ai (i ≤ ai ≤ ai + 1) (but not in the opposite direction), thus there is exactly one shortcut starting at each intersection. Formally, if Mike chooses a sequence p1 = 1, p2, ..., pk then for each 1 ≤ i < k satisfying pi + 1 = api and api ≠ pi Mike will spend only 1 unit of energy instead of |pi - pi + 1| walking from the intersection pi to intersection pi + 1. For example, if Mike chooses a sequence p1 = 1, p2 = ap1, p3 = ap2, ..., pk = apk - 1, he spends exactly k - 1 units of total energy walking around them.
Before going on his adventure, Mike asks you to find the minimum amount of energy required to reach each of the intersections from his home. Formally, for each 1 ≤ i ≤ n Mike is interested in finding minimum possible total energy of some sequence p1 = 1, p2, ..., pk = i.
Input
The first line contains an integer n (1 ≤ n ≤ 200 000) — the number of Mike's city intersection.
The second line contains n integers a1, a2, ..., an (i ≤ ai ≤ n , <image>, describing shortcuts of Mike's city, allowing to walk from intersection i to intersection ai using only 1 unit of energy. Please note that the shortcuts don't allow walking in opposite directions (from ai to i).
Output
In the only line print n integers m1, m2, ..., mn, where mi denotes the least amount of total energy required to walk from intersection 1 to intersection i.
Examples
Input
3
2 2 3
Output
0 1 2
Input
5
1 2 3 4 5
Output
0 1 2 3 4
Input
7
4 4 4 4 7 7 7
Output
0 1 2 1 2 3 3
Note
In the first sample case desired sequences are:
1: 1; m1 = 0;
2: 1, 2; m2 = 1;
3: 1, 3; m3 = |3 - 1| = 2.
In the second sample case the sequence for any intersection 1 < i is always 1, i and mi = |1 - i|.
In the third sample case — consider the following intersection sequences:
1: 1; m1 = 0;
2: 1, 2; m2 = |2 - 1| = 1;
3: 1, 4, 3; m3 = 1 + |4 - 3| = 2;
4: 1, 4; m4 = 1;
5: 1, 4, 5; m5 = 1 + |4 - 5| = 2;
6: 1, 4, 6; m6 = 1 + |4 - 6| = 3;
7: 1, 4, 5, 7; m7 = 1 + |4 - 5| + 1 = 3. | instruction | 0 | 41,674 | 1 | 83,348 |
Tags: dfs and similar, graphs, greedy, shortest paths
Correct Solution:
```
input_n = int(input())
shortcuts = list(map(int,input().split()))
shortcuts = [shortcuts[index]-1 for index in range(input_n)]
result = [-1] * input_n
result[0],index ,f_array = 0,0 , [0]
while index < len(f_array):
found = f_array[index]
index += 1
if result[shortcuts[found]] == -1:
result[shortcuts[found]] = result[found] + 1
f_array.append(shortcuts[found])
if found > 0 and result[found - 1] == -1:
result[found - 1] = result[found] + 1
f_array.append(found - 1)
if found < input_n-1 and result[found + 1] == -1:
result[found + 1] = result[found] + 1
f_array.append(found + 1)
print(*result)
``` | output | 1 | 41,674 | 1 | 83,349 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Recently, Mike was very busy with studying for exams and contests. Now he is going to chill a bit by doing some sight seeing in the city.
City consists of n intersections numbered from 1 to n. Mike starts walking from his house located at the intersection number 1 and goes along some sequence of intersections. Walking from intersection number i to intersection j requires |i - j| units of energy. The total energy spent by Mike to visit a sequence of intersections p1 = 1, p2, ..., pk is equal to <image> units of energy.
Of course, walking would be boring if there were no shortcuts. A shortcut is a special path that allows Mike walking from one intersection to another requiring only 1 unit of energy. There are exactly n shortcuts in Mike's city, the ith of them allows walking from intersection i to intersection ai (i ≤ ai ≤ ai + 1) (but not in the opposite direction), thus there is exactly one shortcut starting at each intersection. Formally, if Mike chooses a sequence p1 = 1, p2, ..., pk then for each 1 ≤ i < k satisfying pi + 1 = api and api ≠ pi Mike will spend only 1 unit of energy instead of |pi - pi + 1| walking from the intersection pi to intersection pi + 1. For example, if Mike chooses a sequence p1 = 1, p2 = ap1, p3 = ap2, ..., pk = apk - 1, he spends exactly k - 1 units of total energy walking around them.
Before going on his adventure, Mike asks you to find the minimum amount of energy required to reach each of the intersections from his home. Formally, for each 1 ≤ i ≤ n Mike is interested in finding minimum possible total energy of some sequence p1 = 1, p2, ..., pk = i.
Input
The first line contains an integer n (1 ≤ n ≤ 200 000) — the number of Mike's city intersection.
The second line contains n integers a1, a2, ..., an (i ≤ ai ≤ n , <image>, describing shortcuts of Mike's city, allowing to walk from intersection i to intersection ai using only 1 unit of energy. Please note that the shortcuts don't allow walking in opposite directions (from ai to i).
Output
In the only line print n integers m1, m2, ..., mn, where mi denotes the least amount of total energy required to walk from intersection 1 to intersection i.
Examples
Input
3
2 2 3
Output
0 1 2
Input
5
1 2 3 4 5
Output
0 1 2 3 4
Input
7
4 4 4 4 7 7 7
Output
0 1 2 1 2 3 3
Note
In the first sample case desired sequences are:
1: 1; m1 = 0;
2: 1, 2; m2 = 1;
3: 1, 3; m3 = |3 - 1| = 2.
In the second sample case the sequence for any intersection 1 < i is always 1, i and mi = |1 - i|.
In the third sample case — consider the following intersection sequences:
1: 1; m1 = 0;
2: 1, 2; m2 = |2 - 1| = 1;
3: 1, 4, 3; m3 = 1 + |4 - 3| = 2;
4: 1, 4; m4 = 1;
5: 1, 4, 5; m5 = 1 + |4 - 5| = 2;
6: 1, 4, 6; m6 = 1 + |4 - 6| = 3;
7: 1, 4, 5, 7; m7 = 1 + |4 - 5| + 1 = 3. | instruction | 0 | 41,675 | 1 | 83,350 |
Tags: dfs and similar, graphs, greedy, shortest paths
Correct Solution:
```
from sys import stdin, stdout
from collections import deque
read, write = stdin.readline, stdout.write
n = int(read())
shortcuts = list(map(lambda x: int(x)-1, read().split()))
graph = [[] for _ in range(n)]
for i in range(n):
graph[i] = list({max(0,i-1),min(n-1,i+1),shortcuts[i]})
queue = deque([(0,0)])
visited = [0] * n
distances = [float('inf')] * n
visited[0],distances[0] = 1,0
while queue:
node, distance = queue.popleft()
for neighbor in graph[node]:
if not visited[neighbor]:
queue.append((neighbor, distance + 1))
distances[neighbor] = distance + 1
visited[neighbor] = 1
write(' '.join(map(str,distances)))
``` | output | 1 | 41,675 | 1 | 83,351 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Recently, Mike was very busy with studying for exams and contests. Now he is going to chill a bit by doing some sight seeing in the city.
City consists of n intersections numbered from 1 to n. Mike starts walking from his house located at the intersection number 1 and goes along some sequence of intersections. Walking from intersection number i to intersection j requires |i - j| units of energy. The total energy spent by Mike to visit a sequence of intersections p1 = 1, p2, ..., pk is equal to <image> units of energy.
Of course, walking would be boring if there were no shortcuts. A shortcut is a special path that allows Mike walking from one intersection to another requiring only 1 unit of energy. There are exactly n shortcuts in Mike's city, the ith of them allows walking from intersection i to intersection ai (i ≤ ai ≤ ai + 1) (but not in the opposite direction), thus there is exactly one shortcut starting at each intersection. Formally, if Mike chooses a sequence p1 = 1, p2, ..., pk then for each 1 ≤ i < k satisfying pi + 1 = api and api ≠ pi Mike will spend only 1 unit of energy instead of |pi - pi + 1| walking from the intersection pi to intersection pi + 1. For example, if Mike chooses a sequence p1 = 1, p2 = ap1, p3 = ap2, ..., pk = apk - 1, he spends exactly k - 1 units of total energy walking around them.
Before going on his adventure, Mike asks you to find the minimum amount of energy required to reach each of the intersections from his home. Formally, for each 1 ≤ i ≤ n Mike is interested in finding minimum possible total energy of some sequence p1 = 1, p2, ..., pk = i.
Input
The first line contains an integer n (1 ≤ n ≤ 200 000) — the number of Mike's city intersection.
The second line contains n integers a1, a2, ..., an (i ≤ ai ≤ n , <image>, describing shortcuts of Mike's city, allowing to walk from intersection i to intersection ai using only 1 unit of energy. Please note that the shortcuts don't allow walking in opposite directions (from ai to i).
Output
In the only line print n integers m1, m2, ..., mn, where mi denotes the least amount of total energy required to walk from intersection 1 to intersection i.
Examples
Input
3
2 2 3
Output
0 1 2
Input
5
1 2 3 4 5
Output
0 1 2 3 4
Input
7
4 4 4 4 7 7 7
Output
0 1 2 1 2 3 3
Note
In the first sample case desired sequences are:
1: 1; m1 = 0;
2: 1, 2; m2 = 1;
3: 1, 3; m3 = |3 - 1| = 2.
In the second sample case the sequence for any intersection 1 < i is always 1, i and mi = |1 - i|.
In the third sample case — consider the following intersection sequences:
1: 1; m1 = 0;
2: 1, 2; m2 = |2 - 1| = 1;
3: 1, 4, 3; m3 = 1 + |4 - 3| = 2;
4: 1, 4; m4 = 1;
5: 1, 4, 5; m5 = 1 + |4 - 5| = 2;
6: 1, 4, 6; m6 = 1 + |4 - 6| = 3;
7: 1, 4, 5, 7; m7 = 1 + |4 - 5| + 1 = 3. | instruction | 0 | 41,676 | 1 | 83,352 |
Tags: dfs and similar, graphs, greedy, shortest paths
Correct Solution:
```
from collections import *
n = int(input())
a = [val - 1 for val in list(map(int, input().split()))]
queue = deque([(0, 0)])
ans = [-1] * n
while len(queue) > 0:
cur = queue.popleft()
if cur[0] < 0 or cur[0] >= n or ans[cur[0]] != -1: continue
ans[cur[0]] = cur[1]
queue.append((cur[0] - 1, cur[1] + 1))
queue.append((cur[0] + 1, cur[1] + 1))
queue.append((a[cur[0]], cur[1] + 1))
print(" ".join(map(str, ans)))
``` | output | 1 | 41,676 | 1 | 83,353 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Recently, Mike was very busy with studying for exams and contests. Now he is going to chill a bit by doing some sight seeing in the city.
City consists of n intersections numbered from 1 to n. Mike starts walking from his house located at the intersection number 1 and goes along some sequence of intersections. Walking from intersection number i to intersection j requires |i - j| units of energy. The total energy spent by Mike to visit a sequence of intersections p1 = 1, p2, ..., pk is equal to <image> units of energy.
Of course, walking would be boring if there were no shortcuts. A shortcut is a special path that allows Mike walking from one intersection to another requiring only 1 unit of energy. There are exactly n shortcuts in Mike's city, the ith of them allows walking from intersection i to intersection ai (i ≤ ai ≤ ai + 1) (but not in the opposite direction), thus there is exactly one shortcut starting at each intersection. Formally, if Mike chooses a sequence p1 = 1, p2, ..., pk then for each 1 ≤ i < k satisfying pi + 1 = api and api ≠ pi Mike will spend only 1 unit of energy instead of |pi - pi + 1| walking from the intersection pi to intersection pi + 1. For example, if Mike chooses a sequence p1 = 1, p2 = ap1, p3 = ap2, ..., pk = apk - 1, he spends exactly k - 1 units of total energy walking around them.
Before going on his adventure, Mike asks you to find the minimum amount of energy required to reach each of the intersections from his home. Formally, for each 1 ≤ i ≤ n Mike is interested in finding minimum possible total energy of some sequence p1 = 1, p2, ..., pk = i.
Input
The first line contains an integer n (1 ≤ n ≤ 200 000) — the number of Mike's city intersection.
The second line contains n integers a1, a2, ..., an (i ≤ ai ≤ n , <image>, describing shortcuts of Mike's city, allowing to walk from intersection i to intersection ai using only 1 unit of energy. Please note that the shortcuts don't allow walking in opposite directions (from ai to i).
Output
In the only line print n integers m1, m2, ..., mn, where mi denotes the least amount of total energy required to walk from intersection 1 to intersection i.
Examples
Input
3
2 2 3
Output
0 1 2
Input
5
1 2 3 4 5
Output
0 1 2 3 4
Input
7
4 4 4 4 7 7 7
Output
0 1 2 1 2 3 3
Note
In the first sample case desired sequences are:
1: 1; m1 = 0;
2: 1, 2; m2 = 1;
3: 1, 3; m3 = |3 - 1| = 2.
In the second sample case the sequence for any intersection 1 < i is always 1, i and mi = |1 - i|.
In the third sample case — consider the following intersection sequences:
1: 1; m1 = 0;
2: 1, 2; m2 = |2 - 1| = 1;
3: 1, 4, 3; m3 = 1 + |4 - 3| = 2;
4: 1, 4; m4 = 1;
5: 1, 4, 5; m5 = 1 + |4 - 5| = 2;
6: 1, 4, 6; m6 = 1 + |4 - 6| = 3;
7: 1, 4, 5, 7; m7 = 1 + |4 - 5| + 1 = 3. | instruction | 0 | 41,677 | 1 | 83,354 |
Tags: dfs and similar, graphs, greedy, shortest paths
Correct Solution:
```
n = int(input())
a = list(map(int, input().split()))
g = []
for i in range(n):
To = set()
if i < n - 1:
To.add(i+1)
if i > 0:
To.add(i-1)
if a[i] - 1 != i:
To.add(a[i]-1)
g.append(To)
q = [0]
used = [i == 0 for i in range(n)]
d = [0 for i in range(n)]
p = [0 for i in range(n)]
p[0] = -1
while len(q) > 0:
v = q[0]
q.pop(0)
for to in g[v]:
if not used[to]:
used[to] = True
q.append(to)
d[to] = d[v] + 1
p[to] = v
for r in d:
print(r, end=' ')
``` | output | 1 | 41,677 | 1 | 83,355 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Recently, Mike was very busy with studying for exams and contests. Now he is going to chill a bit by doing some sight seeing in the city.
City consists of n intersections numbered from 1 to n. Mike starts walking from his house located at the intersection number 1 and goes along some sequence of intersections. Walking from intersection number i to intersection j requires |i - j| units of energy. The total energy spent by Mike to visit a sequence of intersections p1 = 1, p2, ..., pk is equal to <image> units of energy.
Of course, walking would be boring if there were no shortcuts. A shortcut is a special path that allows Mike walking from one intersection to another requiring only 1 unit of energy. There are exactly n shortcuts in Mike's city, the ith of them allows walking from intersection i to intersection ai (i ≤ ai ≤ ai + 1) (but not in the opposite direction), thus there is exactly one shortcut starting at each intersection. Formally, if Mike chooses a sequence p1 = 1, p2, ..., pk then for each 1 ≤ i < k satisfying pi + 1 = api and api ≠ pi Mike will spend only 1 unit of energy instead of |pi - pi + 1| walking from the intersection pi to intersection pi + 1. For example, if Mike chooses a sequence p1 = 1, p2 = ap1, p3 = ap2, ..., pk = apk - 1, he spends exactly k - 1 units of total energy walking around them.
Before going on his adventure, Mike asks you to find the minimum amount of energy required to reach each of the intersections from his home. Formally, for each 1 ≤ i ≤ n Mike is interested in finding minimum possible total energy of some sequence p1 = 1, p2, ..., pk = i.
Input
The first line contains an integer n (1 ≤ n ≤ 200 000) — the number of Mike's city intersection.
The second line contains n integers a1, a2, ..., an (i ≤ ai ≤ n , <image>, describing shortcuts of Mike's city, allowing to walk from intersection i to intersection ai using only 1 unit of energy. Please note that the shortcuts don't allow walking in opposite directions (from ai to i).
Output
In the only line print n integers m1, m2, ..., mn, where mi denotes the least amount of total energy required to walk from intersection 1 to intersection i.
Examples
Input
3
2 2 3
Output
0 1 2
Input
5
1 2 3 4 5
Output
0 1 2 3 4
Input
7
4 4 4 4 7 7 7
Output
0 1 2 1 2 3 3
Note
In the first sample case desired sequences are:
1: 1; m1 = 0;
2: 1, 2; m2 = 1;
3: 1, 3; m3 = |3 - 1| = 2.
In the second sample case the sequence for any intersection 1 < i is always 1, i and mi = |1 - i|.
In the third sample case — consider the following intersection sequences:
1: 1; m1 = 0;
2: 1, 2; m2 = |2 - 1| = 1;
3: 1, 4, 3; m3 = 1 + |4 - 3| = 2;
4: 1, 4; m4 = 1;
5: 1, 4, 5; m5 = 1 + |4 - 5| = 2;
6: 1, 4, 6; m6 = 1 + |4 - 6| = 3;
7: 1, 4, 5, 7; m7 = 1 + |4 - 5| + 1 = 3. | instruction | 0 | 41,678 | 1 | 83,356 |
Tags: dfs and similar, graphs, greedy, shortest paths
Correct Solution:
```
from sys import stdin, stdout
readline, writeline = stdin.readline, stdout.write
n = int(readline().strip())
s = list(map(int, readline().strip().split()))
ans = [0] + [200001] * (n-1)
for i in range(n):
ans[i] = min(ans[i], ans[i-1] + 1)
j = i
if j + 1 < n:
while ans[j+1] + 1 < ans[j]:
ans[j] = ans[j+1] + 1
ans[s[j] - 1] = min(ans[s[j] - 1], ans[j] + 1)
j -= 1
ans[s[i] - 1] = min(ans[s[i] - 1], ans[i] + 1)
for i in range(n):
writeline("{} ".format(ans[i]))
writeline("\n")
``` | output | 1 | 41,678 | 1 | 83,357 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Recently, Mike was very busy with studying for exams and contests. Now he is going to chill a bit by doing some sight seeing in the city.
City consists of n intersections numbered from 1 to n. Mike starts walking from his house located at the intersection number 1 and goes along some sequence of intersections. Walking from intersection number i to intersection j requires |i - j| units of energy. The total energy spent by Mike to visit a sequence of intersections p1 = 1, p2, ..., pk is equal to <image> units of energy.
Of course, walking would be boring if there were no shortcuts. A shortcut is a special path that allows Mike walking from one intersection to another requiring only 1 unit of energy. There are exactly n shortcuts in Mike's city, the ith of them allows walking from intersection i to intersection ai (i ≤ ai ≤ ai + 1) (but not in the opposite direction), thus there is exactly one shortcut starting at each intersection. Formally, if Mike chooses a sequence p1 = 1, p2, ..., pk then for each 1 ≤ i < k satisfying pi + 1 = api and api ≠ pi Mike will spend only 1 unit of energy instead of |pi - pi + 1| walking from the intersection pi to intersection pi + 1. For example, if Mike chooses a sequence p1 = 1, p2 = ap1, p3 = ap2, ..., pk = apk - 1, he spends exactly k - 1 units of total energy walking around them.
Before going on his adventure, Mike asks you to find the minimum amount of energy required to reach each of the intersections from his home. Formally, for each 1 ≤ i ≤ n Mike is interested in finding minimum possible total energy of some sequence p1 = 1, p2, ..., pk = i.
Input
The first line contains an integer n (1 ≤ n ≤ 200 000) — the number of Mike's city intersection.
The second line contains n integers a1, a2, ..., an (i ≤ ai ≤ n , <image>, describing shortcuts of Mike's city, allowing to walk from intersection i to intersection ai using only 1 unit of energy. Please note that the shortcuts don't allow walking in opposite directions (from ai to i).
Output
In the only line print n integers m1, m2, ..., mn, where mi denotes the least amount of total energy required to walk from intersection 1 to intersection i.
Examples
Input
3
2 2 3
Output
0 1 2
Input
5
1 2 3 4 5
Output
0 1 2 3 4
Input
7
4 4 4 4 7 7 7
Output
0 1 2 1 2 3 3
Note
In the first sample case desired sequences are:
1: 1; m1 = 0;
2: 1, 2; m2 = 1;
3: 1, 3; m3 = |3 - 1| = 2.
In the second sample case the sequence for any intersection 1 < i is always 1, i and mi = |1 - i|.
In the third sample case — consider the following intersection sequences:
1: 1; m1 = 0;
2: 1, 2; m2 = |2 - 1| = 1;
3: 1, 4, 3; m3 = 1 + |4 - 3| = 2;
4: 1, 4; m4 = 1;
5: 1, 4, 5; m5 = 1 + |4 - 5| = 2;
6: 1, 4, 6; m6 = 1 + |4 - 6| = 3;
7: 1, 4, 5, 7; m7 = 1 + |4 - 5| + 1 = 3. | instruction | 0 | 41,679 | 1 | 83,358 |
Tags: dfs and similar, graphs, greedy, shortest paths
Correct Solution:
```
n = int(input())
a = list(map(int,input().split()))
dist = [-1] * n
dist[0] = 0
pos = [0]
for i in pos:
for j in [i - 1, i + 1, a[i] - 1]:
if j >= 0 and j < n and dist[j] == -1:
dist[j] = dist[i] + 1
pos.append(j)
print(*dist)
``` | output | 1 | 41,679 | 1 | 83,359 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Recently, Mike was very busy with studying for exams and contests. Now he is going to chill a bit by doing some sight seeing in the city.
City consists of n intersections numbered from 1 to n. Mike starts walking from his house located at the intersection number 1 and goes along some sequence of intersections. Walking from intersection number i to intersection j requires |i - j| units of energy. The total energy spent by Mike to visit a sequence of intersections p1 = 1, p2, ..., pk is equal to <image> units of energy.
Of course, walking would be boring if there were no shortcuts. A shortcut is a special path that allows Mike walking from one intersection to another requiring only 1 unit of energy. There are exactly n shortcuts in Mike's city, the ith of them allows walking from intersection i to intersection ai (i ≤ ai ≤ ai + 1) (but not in the opposite direction), thus there is exactly one shortcut starting at each intersection. Formally, if Mike chooses a sequence p1 = 1, p2, ..., pk then for each 1 ≤ i < k satisfying pi + 1 = api and api ≠ pi Mike will spend only 1 unit of energy instead of |pi - pi + 1| walking from the intersection pi to intersection pi + 1. For example, if Mike chooses a sequence p1 = 1, p2 = ap1, p3 = ap2, ..., pk = apk - 1, he spends exactly k - 1 units of total energy walking around them.
Before going on his adventure, Mike asks you to find the minimum amount of energy required to reach each of the intersections from his home. Formally, for each 1 ≤ i ≤ n Mike is interested in finding minimum possible total energy of some sequence p1 = 1, p2, ..., pk = i.
Input
The first line contains an integer n (1 ≤ n ≤ 200 000) — the number of Mike's city intersection.
The second line contains n integers a1, a2, ..., an (i ≤ ai ≤ n , <image>, describing shortcuts of Mike's city, allowing to walk from intersection i to intersection ai using only 1 unit of energy. Please note that the shortcuts don't allow walking in opposite directions (from ai to i).
Output
In the only line print n integers m1, m2, ..., mn, where mi denotes the least amount of total energy required to walk from intersection 1 to intersection i.
Examples
Input
3
2 2 3
Output
0 1 2
Input
5
1 2 3 4 5
Output
0 1 2 3 4
Input
7
4 4 4 4 7 7 7
Output
0 1 2 1 2 3 3
Note
In the first sample case desired sequences are:
1: 1; m1 = 0;
2: 1, 2; m2 = 1;
3: 1, 3; m3 = |3 - 1| = 2.
In the second sample case the sequence for any intersection 1 < i is always 1, i and mi = |1 - i|.
In the third sample case — consider the following intersection sequences:
1: 1; m1 = 0;
2: 1, 2; m2 = |2 - 1| = 1;
3: 1, 4, 3; m3 = 1 + |4 - 3| = 2;
4: 1, 4; m4 = 1;
5: 1, 4, 5; m5 = 1 + |4 - 5| = 2;
6: 1, 4, 6; m6 = 1 + |4 - 6| = 3;
7: 1, 4, 5, 7; m7 = 1 + |4 - 5| + 1 = 3. | instruction | 0 | 41,680 | 1 | 83,360 |
Tags: dfs and similar, graphs, greedy, shortest paths
Correct Solution:
```
n = int(input())
Ais = list(map(int,input().split()))
Mis = [0] + [-1]*(n-1)
pos = [0]
for i in pos:
n1 = i - 1
n2 = i + 1
n3 = Ais[i] - 1
for j in [n1, n2, n3]:
if j >= 0 and j < n and Mis[j] == -1:
Mis[j] = Mis[i] + 1
pos.append(j)
print(" ".join(map(str, Mis)))
``` | output | 1 | 41,680 | 1 | 83,361 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Recently, Mike was very busy with studying for exams and contests. Now he is going to chill a bit by doing some sight seeing in the city.
City consists of n intersections numbered from 1 to n. Mike starts walking from his house located at the intersection number 1 and goes along some sequence of intersections. Walking from intersection number i to intersection j requires |i - j| units of energy. The total energy spent by Mike to visit a sequence of intersections p1 = 1, p2, ..., pk is equal to <image> units of energy.
Of course, walking would be boring if there were no shortcuts. A shortcut is a special path that allows Mike walking from one intersection to another requiring only 1 unit of energy. There are exactly n shortcuts in Mike's city, the ith of them allows walking from intersection i to intersection ai (i ≤ ai ≤ ai + 1) (but not in the opposite direction), thus there is exactly one shortcut starting at each intersection. Formally, if Mike chooses a sequence p1 = 1, p2, ..., pk then for each 1 ≤ i < k satisfying pi + 1 = api and api ≠ pi Mike will spend only 1 unit of energy instead of |pi - pi + 1| walking from the intersection pi to intersection pi + 1. For example, if Mike chooses a sequence p1 = 1, p2 = ap1, p3 = ap2, ..., pk = apk - 1, he spends exactly k - 1 units of total energy walking around them.
Before going on his adventure, Mike asks you to find the minimum amount of energy required to reach each of the intersections from his home. Formally, for each 1 ≤ i ≤ n Mike is interested in finding minimum possible total energy of some sequence p1 = 1, p2, ..., pk = i.
Input
The first line contains an integer n (1 ≤ n ≤ 200 000) — the number of Mike's city intersection.
The second line contains n integers a1, a2, ..., an (i ≤ ai ≤ n , <image>, describing shortcuts of Mike's city, allowing to walk from intersection i to intersection ai using only 1 unit of energy. Please note that the shortcuts don't allow walking in opposite directions (from ai to i).
Output
In the only line print n integers m1, m2, ..., mn, where mi denotes the least amount of total energy required to walk from intersection 1 to intersection i.
Examples
Input
3
2 2 3
Output
0 1 2
Input
5
1 2 3 4 5
Output
0 1 2 3 4
Input
7
4 4 4 4 7 7 7
Output
0 1 2 1 2 3 3
Note
In the first sample case desired sequences are:
1: 1; m1 = 0;
2: 1, 2; m2 = 1;
3: 1, 3; m3 = |3 - 1| = 2.
In the second sample case the sequence for any intersection 1 < i is always 1, i and mi = |1 - i|.
In the third sample case — consider the following intersection sequences:
1: 1; m1 = 0;
2: 1, 2; m2 = |2 - 1| = 1;
3: 1, 4, 3; m3 = 1 + |4 - 3| = 2;
4: 1, 4; m4 = 1;
5: 1, 4, 5; m5 = 1 + |4 - 5| = 2;
6: 1, 4, 6; m6 = 1 + |4 - 6| = 3;
7: 1, 4, 5, 7; m7 = 1 + |4 - 5| + 1 = 3.
Submitted Solution:
```
def bfs():
while len(queue)>0:
current=queue.pop(0)
if current<n and dis[current+1]>dis[current]+1:
dis[current+1]=dis[current]+1
queue.append(current+1)
if current>1 and dis[current-1]>dis[current]+1:
dis[current-1]=dis[current]+1
queue.append(current-1)
if dis[shortlist[current]]>dis[current]+1:
dis[shortlist[current]]=dis[current]+1
queue.append(shortlist[current])
n=int(input())
input2=input().split()
shortlist=[0]+[int(x) for x in input2]
dis=[float('inf') for x in range(n+1)]
dis[1]=0
queue=[1]
bfs()
print(' '.join(str(i) for i in dis[1:]))
``` | instruction | 0 | 41,681 | 1 | 83,362 |
Yes | output | 1 | 41,681 | 1 | 83,363 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Recently, Mike was very busy with studying for exams and contests. Now he is going to chill a bit by doing some sight seeing in the city.
City consists of n intersections numbered from 1 to n. Mike starts walking from his house located at the intersection number 1 and goes along some sequence of intersections. Walking from intersection number i to intersection j requires |i - j| units of energy. The total energy spent by Mike to visit a sequence of intersections p1 = 1, p2, ..., pk is equal to <image> units of energy.
Of course, walking would be boring if there were no shortcuts. A shortcut is a special path that allows Mike walking from one intersection to another requiring only 1 unit of energy. There are exactly n shortcuts in Mike's city, the ith of them allows walking from intersection i to intersection ai (i ≤ ai ≤ ai + 1) (but not in the opposite direction), thus there is exactly one shortcut starting at each intersection. Formally, if Mike chooses a sequence p1 = 1, p2, ..., pk then for each 1 ≤ i < k satisfying pi + 1 = api and api ≠ pi Mike will spend only 1 unit of energy instead of |pi - pi + 1| walking from the intersection pi to intersection pi + 1. For example, if Mike chooses a sequence p1 = 1, p2 = ap1, p3 = ap2, ..., pk = apk - 1, he spends exactly k - 1 units of total energy walking around them.
Before going on his adventure, Mike asks you to find the minimum amount of energy required to reach each of the intersections from his home. Formally, for each 1 ≤ i ≤ n Mike is interested in finding minimum possible total energy of some sequence p1 = 1, p2, ..., pk = i.
Input
The first line contains an integer n (1 ≤ n ≤ 200 000) — the number of Mike's city intersection.
The second line contains n integers a1, a2, ..., an (i ≤ ai ≤ n , <image>, describing shortcuts of Mike's city, allowing to walk from intersection i to intersection ai using only 1 unit of energy. Please note that the shortcuts don't allow walking in opposite directions (from ai to i).
Output
In the only line print n integers m1, m2, ..., mn, where mi denotes the least amount of total energy required to walk from intersection 1 to intersection i.
Examples
Input
3
2 2 3
Output
0 1 2
Input
5
1 2 3 4 5
Output
0 1 2 3 4
Input
7
4 4 4 4 7 7 7
Output
0 1 2 1 2 3 3
Note
In the first sample case desired sequences are:
1: 1; m1 = 0;
2: 1, 2; m2 = 1;
3: 1, 3; m3 = |3 - 1| = 2.
In the second sample case the sequence for any intersection 1 < i is always 1, i and mi = |1 - i|.
In the third sample case — consider the following intersection sequences:
1: 1; m1 = 0;
2: 1, 2; m2 = |2 - 1| = 1;
3: 1, 4, 3; m3 = 1 + |4 - 3| = 2;
4: 1, 4; m4 = 1;
5: 1, 4, 5; m5 = 1 + |4 - 5| = 2;
6: 1, 4, 6; m6 = 1 + |4 - 6| = 3;
7: 1, 4, 5, 7; m7 = 1 + |4 - 5| + 1 = 3.
Submitted Solution:
```
def solve(n, g):
ans = [float('inf')] * (n+1)
ans[1] = 0
q = [1]
while q:
t = q.pop(0)
if t+1 <=n and ans[t]+1 < ans[t+1]:
ans[t+1]=ans[t]+1
q.append(t+1)
if t-1 >=1 and ans[t]+1 < ans[t-1]:
ans[t-1]=ans[t]+1
q.append(t-1)
if ans[t]+1 < ans[g[t]]:
ans[g[t]]=ans[t]+1
q.append(g[t])
return ans
if __name__ == '__main__':
n = int(input())
g = list(map(int, input().split()))
g.insert(0,0)
ans = solve(n, g)
res = ' '.join([str(i) for i in ans[1:]])
print(res)
``` | instruction | 0 | 41,682 | 1 | 83,364 |
Yes | output | 1 | 41,682 | 1 | 83,365 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Recently, Mike was very busy with studying for exams and contests. Now he is going to chill a bit by doing some sight seeing in the city.
City consists of n intersections numbered from 1 to n. Mike starts walking from his house located at the intersection number 1 and goes along some sequence of intersections. Walking from intersection number i to intersection j requires |i - j| units of energy. The total energy spent by Mike to visit a sequence of intersections p1 = 1, p2, ..., pk is equal to <image> units of energy.
Of course, walking would be boring if there were no shortcuts. A shortcut is a special path that allows Mike walking from one intersection to another requiring only 1 unit of energy. There are exactly n shortcuts in Mike's city, the ith of them allows walking from intersection i to intersection ai (i ≤ ai ≤ ai + 1) (but not in the opposite direction), thus there is exactly one shortcut starting at each intersection. Formally, if Mike chooses a sequence p1 = 1, p2, ..., pk then for each 1 ≤ i < k satisfying pi + 1 = api and api ≠ pi Mike will spend only 1 unit of energy instead of |pi - pi + 1| walking from the intersection pi to intersection pi + 1. For example, if Mike chooses a sequence p1 = 1, p2 = ap1, p3 = ap2, ..., pk = apk - 1, he spends exactly k - 1 units of total energy walking around them.
Before going on his adventure, Mike asks you to find the minimum amount of energy required to reach each of the intersections from his home. Formally, for each 1 ≤ i ≤ n Mike is interested in finding minimum possible total energy of some sequence p1 = 1, p2, ..., pk = i.
Input
The first line contains an integer n (1 ≤ n ≤ 200 000) — the number of Mike's city intersection.
The second line contains n integers a1, a2, ..., an (i ≤ ai ≤ n , <image>, describing shortcuts of Mike's city, allowing to walk from intersection i to intersection ai using only 1 unit of energy. Please note that the shortcuts don't allow walking in opposite directions (from ai to i).
Output
In the only line print n integers m1, m2, ..., mn, where mi denotes the least amount of total energy required to walk from intersection 1 to intersection i.
Examples
Input
3
2 2 3
Output
0 1 2
Input
5
1 2 3 4 5
Output
0 1 2 3 4
Input
7
4 4 4 4 7 7 7
Output
0 1 2 1 2 3 3
Note
In the first sample case desired sequences are:
1: 1; m1 = 0;
2: 1, 2; m2 = 1;
3: 1, 3; m3 = |3 - 1| = 2.
In the second sample case the sequence for any intersection 1 < i is always 1, i and mi = |1 - i|.
In the third sample case — consider the following intersection sequences:
1: 1; m1 = 0;
2: 1, 2; m2 = |2 - 1| = 1;
3: 1, 4, 3; m3 = 1 + |4 - 3| = 2;
4: 1, 4; m4 = 1;
5: 1, 4, 5; m5 = 1 + |4 - 5| = 2;
6: 1, 4, 6; m6 = 1 + |4 - 6| = 3;
7: 1, 4, 5, 7; m7 = 1 + |4 - 5| + 1 = 3.
Submitted Solution:
```
n = int(input())
a = list(map(int,input().split()))
dist = [-1] * n
dist[0] = 0
pos = [0]
for u in pos:
for v in [u - 1, u + 1, a[u] - 1]:
if v >= 0 and v < n and dist[v] == -1:
dist[v] = dist[u] + 1
pos.append(v)
print(" ".join(map(str, dist)))
``` | instruction | 0 | 41,683 | 1 | 83,366 |
Yes | output | 1 | 41,683 | 1 | 83,367 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Recently, Mike was very busy with studying for exams and contests. Now he is going to chill a bit by doing some sight seeing in the city.
City consists of n intersections numbered from 1 to n. Mike starts walking from his house located at the intersection number 1 and goes along some sequence of intersections. Walking from intersection number i to intersection j requires |i - j| units of energy. The total energy spent by Mike to visit a sequence of intersections p1 = 1, p2, ..., pk is equal to <image> units of energy.
Of course, walking would be boring if there were no shortcuts. A shortcut is a special path that allows Mike walking from one intersection to another requiring only 1 unit of energy. There are exactly n shortcuts in Mike's city, the ith of them allows walking from intersection i to intersection ai (i ≤ ai ≤ ai + 1) (but not in the opposite direction), thus there is exactly one shortcut starting at each intersection. Formally, if Mike chooses a sequence p1 = 1, p2, ..., pk then for each 1 ≤ i < k satisfying pi + 1 = api and api ≠ pi Mike will spend only 1 unit of energy instead of |pi - pi + 1| walking from the intersection pi to intersection pi + 1. For example, if Mike chooses a sequence p1 = 1, p2 = ap1, p3 = ap2, ..., pk = apk - 1, he spends exactly k - 1 units of total energy walking around them.
Before going on his adventure, Mike asks you to find the minimum amount of energy required to reach each of the intersections from his home. Formally, for each 1 ≤ i ≤ n Mike is interested in finding minimum possible total energy of some sequence p1 = 1, p2, ..., pk = i.
Input
The first line contains an integer n (1 ≤ n ≤ 200 000) — the number of Mike's city intersection.
The second line contains n integers a1, a2, ..., an (i ≤ ai ≤ n , <image>, describing shortcuts of Mike's city, allowing to walk from intersection i to intersection ai using only 1 unit of energy. Please note that the shortcuts don't allow walking in opposite directions (from ai to i).
Output
In the only line print n integers m1, m2, ..., mn, where mi denotes the least amount of total energy required to walk from intersection 1 to intersection i.
Examples
Input
3
2 2 3
Output
0 1 2
Input
5
1 2 3 4 5
Output
0 1 2 3 4
Input
7
4 4 4 4 7 7 7
Output
0 1 2 1 2 3 3
Note
In the first sample case desired sequences are:
1: 1; m1 = 0;
2: 1, 2; m2 = 1;
3: 1, 3; m3 = |3 - 1| = 2.
In the second sample case the sequence for any intersection 1 < i is always 1, i and mi = |1 - i|.
In the third sample case — consider the following intersection sequences:
1: 1; m1 = 0;
2: 1, 2; m2 = |2 - 1| = 1;
3: 1, 4, 3; m3 = 1 + |4 - 3| = 2;
4: 1, 4; m4 = 1;
5: 1, 4, 5; m5 = 1 + |4 - 5| = 2;
6: 1, 4, 6; m6 = 1 + |4 - 6| = 3;
7: 1, 4, 5, 7; m7 = 1 + |4 - 5| + 1 = 3.
Submitted Solution:
```
n=int(input())
l=list(map(int, input().split(' ')))
out=[-1]*n
pas = 0
pos = [0]
out[0]=0
while pos :
pas+=1
new_pos=[]
for p in pos :
for q in [p-1,p+1,l[p]-1] :
if q>=0 and q<n and out[q]==-1:
out[q]=pas
new_pos.append(q)
pos = new_pos
print(*out)
``` | instruction | 0 | 41,684 | 1 | 83,368 |
Yes | output | 1 | 41,684 | 1 | 83,369 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Recently, Mike was very busy with studying for exams and contests. Now he is going to chill a bit by doing some sight seeing in the city.
City consists of n intersections numbered from 1 to n. Mike starts walking from his house located at the intersection number 1 and goes along some sequence of intersections. Walking from intersection number i to intersection j requires |i - j| units of energy. The total energy spent by Mike to visit a sequence of intersections p1 = 1, p2, ..., pk is equal to <image> units of energy.
Of course, walking would be boring if there were no shortcuts. A shortcut is a special path that allows Mike walking from one intersection to another requiring only 1 unit of energy. There are exactly n shortcuts in Mike's city, the ith of them allows walking from intersection i to intersection ai (i ≤ ai ≤ ai + 1) (but not in the opposite direction), thus there is exactly one shortcut starting at each intersection. Formally, if Mike chooses a sequence p1 = 1, p2, ..., pk then for each 1 ≤ i < k satisfying pi + 1 = api and api ≠ pi Mike will spend only 1 unit of energy instead of |pi - pi + 1| walking from the intersection pi to intersection pi + 1. For example, if Mike chooses a sequence p1 = 1, p2 = ap1, p3 = ap2, ..., pk = apk - 1, he spends exactly k - 1 units of total energy walking around them.
Before going on his adventure, Mike asks you to find the minimum amount of energy required to reach each of the intersections from his home. Formally, for each 1 ≤ i ≤ n Mike is interested in finding minimum possible total energy of some sequence p1 = 1, p2, ..., pk = i.
Input
The first line contains an integer n (1 ≤ n ≤ 200 000) — the number of Mike's city intersection.
The second line contains n integers a1, a2, ..., an (i ≤ ai ≤ n , <image>, describing shortcuts of Mike's city, allowing to walk from intersection i to intersection ai using only 1 unit of energy. Please note that the shortcuts don't allow walking in opposite directions (from ai to i).
Output
In the only line print n integers m1, m2, ..., mn, where mi denotes the least amount of total energy required to walk from intersection 1 to intersection i.
Examples
Input
3
2 2 3
Output
0 1 2
Input
5
1 2 3 4 5
Output
0 1 2 3 4
Input
7
4 4 4 4 7 7 7
Output
0 1 2 1 2 3 3
Note
In the first sample case desired sequences are:
1: 1; m1 = 0;
2: 1, 2; m2 = 1;
3: 1, 3; m3 = |3 - 1| = 2.
In the second sample case the sequence for any intersection 1 < i is always 1, i and mi = |1 - i|.
In the third sample case — consider the following intersection sequences:
1: 1; m1 = 0;
2: 1, 2; m2 = |2 - 1| = 1;
3: 1, 4, 3; m3 = 1 + |4 - 3| = 2;
4: 1, 4; m4 = 1;
5: 1, 4, 5; m5 = 1 + |4 - 5| = 2;
6: 1, 4, 6; m6 = 1 + |4 - 6| = 3;
7: 1, 4, 5, 7; m7 = 1 + |4 - 5| + 1 = 3.
Submitted Solution:
```
# Aluno Rafael Pontes
import queue
n = int(input())
cortes = [int(x) for x in input().split()]
cortes = [0] + cortes
distancias = [-1] * (n + 1)
fila = queue.Queue()
distancias[1] = 0
fila.put(1)
while(fila.qsize() > 0):
k = fila.get()
if (k + 1 <= n and distancias[k + 1] == -1):
distancias[k + 1] = distancias[k] + 1
fila.put(k + 1)
if (distancias[cortes[k]] == -1):
distancias[cortes[k]] = distancias[k] + 1
fila.put(cortes[k])
if (k - 1 > 0 and distancias[k - 1] == -1):
distancias[k - 1] = distancias[k] + 1
fila.put(k - 1)
for i in range(n):
print("%d " % (distancias[i] + 1), end="")
``` | instruction | 0 | 41,685 | 1 | 83,370 |
No | output | 1 | 41,685 | 1 | 83,371 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Recently, Mike was very busy with studying for exams and contests. Now he is going to chill a bit by doing some sight seeing in the city.
City consists of n intersections numbered from 1 to n. Mike starts walking from his house located at the intersection number 1 and goes along some sequence of intersections. Walking from intersection number i to intersection j requires |i - j| units of energy. The total energy spent by Mike to visit a sequence of intersections p1 = 1, p2, ..., pk is equal to <image> units of energy.
Of course, walking would be boring if there were no shortcuts. A shortcut is a special path that allows Mike walking from one intersection to another requiring only 1 unit of energy. There are exactly n shortcuts in Mike's city, the ith of them allows walking from intersection i to intersection ai (i ≤ ai ≤ ai + 1) (but not in the opposite direction), thus there is exactly one shortcut starting at each intersection. Formally, if Mike chooses a sequence p1 = 1, p2, ..., pk then for each 1 ≤ i < k satisfying pi + 1 = api and api ≠ pi Mike will spend only 1 unit of energy instead of |pi - pi + 1| walking from the intersection pi to intersection pi + 1. For example, if Mike chooses a sequence p1 = 1, p2 = ap1, p3 = ap2, ..., pk = apk - 1, he spends exactly k - 1 units of total energy walking around them.
Before going on his adventure, Mike asks you to find the minimum amount of energy required to reach each of the intersections from his home. Formally, for each 1 ≤ i ≤ n Mike is interested in finding minimum possible total energy of some sequence p1 = 1, p2, ..., pk = i.
Input
The first line contains an integer n (1 ≤ n ≤ 200 000) — the number of Mike's city intersection.
The second line contains n integers a1, a2, ..., an (i ≤ ai ≤ n , <image>, describing shortcuts of Mike's city, allowing to walk from intersection i to intersection ai using only 1 unit of energy. Please note that the shortcuts don't allow walking in opposite directions (from ai to i).
Output
In the only line print n integers m1, m2, ..., mn, where mi denotes the least amount of total energy required to walk from intersection 1 to intersection i.
Examples
Input
3
2 2 3
Output
0 1 2
Input
5
1 2 3 4 5
Output
0 1 2 3 4
Input
7
4 4 4 4 7 7 7
Output
0 1 2 1 2 3 3
Note
In the first sample case desired sequences are:
1: 1; m1 = 0;
2: 1, 2; m2 = 1;
3: 1, 3; m3 = |3 - 1| = 2.
In the second sample case the sequence for any intersection 1 < i is always 1, i and mi = |1 - i|.
In the third sample case — consider the following intersection sequences:
1: 1; m1 = 0;
2: 1, 2; m2 = |2 - 1| = 1;
3: 1, 4, 3; m3 = 1 + |4 - 3| = 2;
4: 1, 4; m4 = 1;
5: 1, 4, 5; m5 = 1 + |4 - 5| = 2;
6: 1, 4, 6; m6 = 1 + |4 - 6| = 3;
7: 1, 4, 5, 7; m7 = 1 + |4 - 5| + 1 = 3.
Submitted Solution:
```
def main():
n=int(input())
r=list(map(int, input().split()))
x=[a+1 for a in range(n+1)]
for i in range(len(r)):
x[i+1]=r[i]
for dest in range(1, n+1):
p=1
nrj=0
while p!=dest:
nrj+=1
if x[p]<=dest and x[p]>p:
p=x[p]
else:
p+=1
print(nrj, end="")
main()
``` | instruction | 0 | 41,686 | 1 | 83,372 |
No | output | 1 | 41,686 | 1 | 83,373 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Recently, Mike was very busy with studying for exams and contests. Now he is going to chill a bit by doing some sight seeing in the city.
City consists of n intersections numbered from 1 to n. Mike starts walking from his house located at the intersection number 1 and goes along some sequence of intersections. Walking from intersection number i to intersection j requires |i - j| units of energy. The total energy spent by Mike to visit a sequence of intersections p1 = 1, p2, ..., pk is equal to <image> units of energy.
Of course, walking would be boring if there were no shortcuts. A shortcut is a special path that allows Mike walking from one intersection to another requiring only 1 unit of energy. There are exactly n shortcuts in Mike's city, the ith of them allows walking from intersection i to intersection ai (i ≤ ai ≤ ai + 1) (but not in the opposite direction), thus there is exactly one shortcut starting at each intersection. Formally, if Mike chooses a sequence p1 = 1, p2, ..., pk then for each 1 ≤ i < k satisfying pi + 1 = api and api ≠ pi Mike will spend only 1 unit of energy instead of |pi - pi + 1| walking from the intersection pi to intersection pi + 1. For example, if Mike chooses a sequence p1 = 1, p2 = ap1, p3 = ap2, ..., pk = apk - 1, he spends exactly k - 1 units of total energy walking around them.
Before going on his adventure, Mike asks you to find the minimum amount of energy required to reach each of the intersections from his home. Formally, for each 1 ≤ i ≤ n Mike is interested in finding minimum possible total energy of some sequence p1 = 1, p2, ..., pk = i.
Input
The first line contains an integer n (1 ≤ n ≤ 200 000) — the number of Mike's city intersection.
The second line contains n integers a1, a2, ..., an (i ≤ ai ≤ n , <image>, describing shortcuts of Mike's city, allowing to walk from intersection i to intersection ai using only 1 unit of energy. Please note that the shortcuts don't allow walking in opposite directions (from ai to i).
Output
In the only line print n integers m1, m2, ..., mn, where mi denotes the least amount of total energy required to walk from intersection 1 to intersection i.
Examples
Input
3
2 2 3
Output
0 1 2
Input
5
1 2 3 4 5
Output
0 1 2 3 4
Input
7
4 4 4 4 7 7 7
Output
0 1 2 1 2 3 3
Note
In the first sample case desired sequences are:
1: 1; m1 = 0;
2: 1, 2; m2 = 1;
3: 1, 3; m3 = |3 - 1| = 2.
In the second sample case the sequence for any intersection 1 < i is always 1, i and mi = |1 - i|.
In the third sample case — consider the following intersection sequences:
1: 1; m1 = 0;
2: 1, 2; m2 = |2 - 1| = 1;
3: 1, 4, 3; m3 = 1 + |4 - 3| = 2;
4: 1, 4; m4 = 1;
5: 1, 4, 5; m5 = 1 + |4 - 5| = 2;
6: 1, 4, 6; m6 = 1 + |4 - 6| = 3;
7: 1, 4, 5, 7; m7 = 1 + |4 - 5| + 1 = 3.
Submitted Solution:
```
from collections import defaultdict
n = int(input())
shortcuts = list(map(int, input().split()))
graph = defaultdict(set)
for i in range(n):
if i != 0:
graph[i].add(i - 1)
if i != n - 1:
graph[i].add(i + 1)
graph[shortcuts[i] - 1].add(i)
distances = []
for i in range(n):
min_dist = 200001
if (i == 0):
min_dist = 0
for j in graph[i]:
if j < i:
dist_j = 1 + distances[j]
if dist_j < min_dist:
min_dist = dist_j
distances.append(min_dist)
for i in range(n - 2, -1, -1):
if (distances[i + 1] + 1 < distances[i]):
distances[i] = distances[i + 1] + 1
print(' '.join([str(int) for int in distances]))
``` | instruction | 0 | 41,687 | 1 | 83,374 |
No | output | 1 | 41,687 | 1 | 83,375 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Recently, Mike was very busy with studying for exams and contests. Now he is going to chill a bit by doing some sight seeing in the city.
City consists of n intersections numbered from 1 to n. Mike starts walking from his house located at the intersection number 1 and goes along some sequence of intersections. Walking from intersection number i to intersection j requires |i - j| units of energy. The total energy spent by Mike to visit a sequence of intersections p1 = 1, p2, ..., pk is equal to <image> units of energy.
Of course, walking would be boring if there were no shortcuts. A shortcut is a special path that allows Mike walking from one intersection to another requiring only 1 unit of energy. There are exactly n shortcuts in Mike's city, the ith of them allows walking from intersection i to intersection ai (i ≤ ai ≤ ai + 1) (but not in the opposite direction), thus there is exactly one shortcut starting at each intersection. Formally, if Mike chooses a sequence p1 = 1, p2, ..., pk then for each 1 ≤ i < k satisfying pi + 1 = api and api ≠ pi Mike will spend only 1 unit of energy instead of |pi - pi + 1| walking from the intersection pi to intersection pi + 1. For example, if Mike chooses a sequence p1 = 1, p2 = ap1, p3 = ap2, ..., pk = apk - 1, he spends exactly k - 1 units of total energy walking around them.
Before going on his adventure, Mike asks you to find the minimum amount of energy required to reach each of the intersections from his home. Formally, for each 1 ≤ i ≤ n Mike is interested in finding minimum possible total energy of some sequence p1 = 1, p2, ..., pk = i.
Input
The first line contains an integer n (1 ≤ n ≤ 200 000) — the number of Mike's city intersection.
The second line contains n integers a1, a2, ..., an (i ≤ ai ≤ n , <image>, describing shortcuts of Mike's city, allowing to walk from intersection i to intersection ai using only 1 unit of energy. Please note that the shortcuts don't allow walking in opposite directions (from ai to i).
Output
In the only line print n integers m1, m2, ..., mn, where mi denotes the least amount of total energy required to walk from intersection 1 to intersection i.
Examples
Input
3
2 2 3
Output
0 1 2
Input
5
1 2 3 4 5
Output
0 1 2 3 4
Input
7
4 4 4 4 7 7 7
Output
0 1 2 1 2 3 3
Note
In the first sample case desired sequences are:
1: 1; m1 = 0;
2: 1, 2; m2 = 1;
3: 1, 3; m3 = |3 - 1| = 2.
In the second sample case the sequence for any intersection 1 < i is always 1, i and mi = |1 - i|.
In the third sample case — consider the following intersection sequences:
1: 1; m1 = 0;
2: 1, 2; m2 = |2 - 1| = 1;
3: 1, 4, 3; m3 = 1 + |4 - 3| = 2;
4: 1, 4; m4 = 1;
5: 1, 4, 5; m5 = 1 + |4 - 5| = 2;
6: 1, 4, 6; m6 = 1 + |4 - 6| = 3;
7: 1, 4, 5, 7; m7 = 1 + |4 - 5| + 1 = 3.
Submitted Solution:
```
import sys
input=sys.stdin.readline
from collections import deque
#sys.setrecursionlimit(10**8)
t=1
import math
def bfs(a,i,dis,vis):
vis[i]=1
pp=deque()
pp.append(i)
while len(pp)!=0:
z=pp[0]
vis[z]=1
pp.popleft()
for j in a[z]:
if vis[j]==0:
dis[j]=min(dis[j],dis[z]+1)
pp.append(j)
while t>0:
t-=1
n=int(input())
b=[int(x) for x in input().split()]
a=[[] for i in range(n+1)]
for i in range(n):
x=i+1
y=b[i]
if x==y:
continue
a[x].append(y)
a[y].append(x)
vis=[0 for i in range(n+1)]
dis=[i-1 for i in range(n+1)]
bfs(a,1,dis,vis)
for i in range(1,n):
dis[i+1]=min(dis[i+1],dis[i]+1)
#print(*vis)
for i in range(1,n+1):
if vis[i]==0:
bfs(a,i,dis,vis)
print(*dis[1:])
``` | instruction | 0 | 41,688 | 1 | 83,376 |
No | output | 1 | 41,688 | 1 | 83,377 |
Provide a correct Python 3 solution for this coding contest problem.
Every day, N passengers arrive at Takahashi Airport. The i-th passenger arrives at time T_i.
Every passenger arrived at Takahashi airport travels to the city by bus. Each bus can accommodate up to C passengers. Naturally, a passenger cannot take a bus that departs earlier than the airplane arrives at the airport. Also, a passenger will get angry if he/she is still unable to take a bus K units of time after the arrival of the airplane. For that reason, it is necessary to arrange buses so that the i-th passenger can take a bus departing at time between T_i and T_i + K (inclusive).
When setting the departure times for buses under this condition, find the minimum required number of buses. Here, the departure time for each bus does not need to be an integer, and there may be multiple buses that depart at the same time.
Constraints
* 2 \leq N \leq 100000
* 1 \leq C \leq 10^9
* 1 \leq K \leq 10^9
* 1 \leq T_i \leq 10^9
* C, K and T_i are integers.
Input
The input is given from Standard Input in the following format:
N C K
T_1
T_2
:
T_N
Output
Print the minimum required number of buses.
Examples
Input
5 3 5
1
2
3
6
12
Output
3
Input
6 3 3
7
6
2
8
10
6
Output
3 | instruction | 0 | 41,941 | 1 | 83,882 |
"Correct Solution:
```
n, c, k = map(int, input().split())
s = [int(input()) for _ in range(n)]
s = sorted(s)
num = 0
i = s[0]
m = s[0] + k
p = 1
for j in s[1:]:
if j <= m and p < c:
p += 1
else:
p = 1
num += 1
m = j + k
i = j
num += 1
print(num)
``` | output | 1 | 41,941 | 1 | 83,883 |
Provide a correct Python 3 solution for this coding contest problem.
Every day, N passengers arrive at Takahashi Airport. The i-th passenger arrives at time T_i.
Every passenger arrived at Takahashi airport travels to the city by bus. Each bus can accommodate up to C passengers. Naturally, a passenger cannot take a bus that departs earlier than the airplane arrives at the airport. Also, a passenger will get angry if he/she is still unable to take a bus K units of time after the arrival of the airplane. For that reason, it is necessary to arrange buses so that the i-th passenger can take a bus departing at time between T_i and T_i + K (inclusive).
When setting the departure times for buses under this condition, find the minimum required number of buses. Here, the departure time for each bus does not need to be an integer, and there may be multiple buses that depart at the same time.
Constraints
* 2 \leq N \leq 100000
* 1 \leq C \leq 10^9
* 1 \leq K \leq 10^9
* 1 \leq T_i \leq 10^9
* C, K and T_i are integers.
Input
The input is given from Standard Input in the following format:
N C K
T_1
T_2
:
T_N
Output
Print the minimum required number of buses.
Examples
Input
5 3 5
1
2
3
6
12
Output
3
Input
6 3 3
7
6
2
8
10
6
Output
3 | instruction | 0 | 41,942 | 1 | 83,884 |
"Correct Solution:
```
n,c,k=map(int,input().split())
t=[]
for i in range(n):
t.append(int(input()))
t.sort()
cnt=1
s=0
for i in range(1,n):
if i==s+c or t[i]>t[s]+k:
s=i
cnt+=1
print(cnt)
``` | output | 1 | 41,942 | 1 | 83,885 |
Provide a correct Python 3 solution for this coding contest problem.
Every day, N passengers arrive at Takahashi Airport. The i-th passenger arrives at time T_i.
Every passenger arrived at Takahashi airport travels to the city by bus. Each bus can accommodate up to C passengers. Naturally, a passenger cannot take a bus that departs earlier than the airplane arrives at the airport. Also, a passenger will get angry if he/she is still unable to take a bus K units of time after the arrival of the airplane. For that reason, it is necessary to arrange buses so that the i-th passenger can take a bus departing at time between T_i and T_i + K (inclusive).
When setting the departure times for buses under this condition, find the minimum required number of buses. Here, the departure time for each bus does not need to be an integer, and there may be multiple buses that depart at the same time.
Constraints
* 2 \leq N \leq 100000
* 1 \leq C \leq 10^9
* 1 \leq K \leq 10^9
* 1 \leq T_i \leq 10^9
* C, K and T_i are integers.
Input
The input is given from Standard Input in the following format:
N C K
T_1
T_2
:
T_N
Output
Print the minimum required number of buses.
Examples
Input
5 3 5
1
2
3
6
12
Output
3
Input
6 3 3
7
6
2
8
10
6
Output
3 | instruction | 0 | 41,943 | 1 | 83,886 |
"Correct Solution:
```
N,C,K = map(int,input().split())
T = []
for i in range(N):
T.append(int(input()))
T.sort()
ans = 0
p = C
d_time = 0
for i in range(N):
if T[i] - d_time > K or p == C:
ans += 1
d_time = T[i]
p = 1
else:
p += 1
print(ans)
``` | output | 1 | 41,943 | 1 | 83,887 |
Provide a correct Python 3 solution for this coding contest problem.
Every day, N passengers arrive at Takahashi Airport. The i-th passenger arrives at time T_i.
Every passenger arrived at Takahashi airport travels to the city by bus. Each bus can accommodate up to C passengers. Naturally, a passenger cannot take a bus that departs earlier than the airplane arrives at the airport. Also, a passenger will get angry if he/she is still unable to take a bus K units of time after the arrival of the airplane. For that reason, it is necessary to arrange buses so that the i-th passenger can take a bus departing at time between T_i and T_i + K (inclusive).
When setting the departure times for buses under this condition, find the minimum required number of buses. Here, the departure time for each bus does not need to be an integer, and there may be multiple buses that depart at the same time.
Constraints
* 2 \leq N \leq 100000
* 1 \leq C \leq 10^9
* 1 \leq K \leq 10^9
* 1 \leq T_i \leq 10^9
* C, K and T_i are integers.
Input
The input is given from Standard Input in the following format:
N C K
T_1
T_2
:
T_N
Output
Print the minimum required number of buses.
Examples
Input
5 3 5
1
2
3
6
12
Output
3
Input
6 3 3
7
6
2
8
10
6
Output
3 | instruction | 0 | 41,944 | 1 | 83,888 |
"Correct Solution:
```
n,c,k=map(int,input().split())
t=[]
for i in range(n):
t.append(int(input()))
t.sort()
ans=0
p=0
q=0
for i in range(n):
if p==0:
p=t[i]
ans+=1
q=i
elif t[i]>p+k or i>=q+c:
p=t[i]
ans+=1
q=i
print(ans)
``` | output | 1 | 41,944 | 1 | 83,889 |
Provide a correct Python 3 solution for this coding contest problem.
Every day, N passengers arrive at Takahashi Airport. The i-th passenger arrives at time T_i.
Every passenger arrived at Takahashi airport travels to the city by bus. Each bus can accommodate up to C passengers. Naturally, a passenger cannot take a bus that departs earlier than the airplane arrives at the airport. Also, a passenger will get angry if he/she is still unable to take a bus K units of time after the arrival of the airplane. For that reason, it is necessary to arrange buses so that the i-th passenger can take a bus departing at time between T_i and T_i + K (inclusive).
When setting the departure times for buses under this condition, find the minimum required number of buses. Here, the departure time for each bus does not need to be an integer, and there may be multiple buses that depart at the same time.
Constraints
* 2 \leq N \leq 100000
* 1 \leq C \leq 10^9
* 1 \leq K \leq 10^9
* 1 \leq T_i \leq 10^9
* C, K and T_i are integers.
Input
The input is given from Standard Input in the following format:
N C K
T_1
T_2
:
T_N
Output
Print the minimum required number of buses.
Examples
Input
5 3 5
1
2
3
6
12
Output
3
Input
6 3 3
7
6
2
8
10
6
Output
3 | instruction | 0 | 41,945 | 1 | 83,890 |
"Correct Solution:
```
N, C, K = [int(i) for i in input().split()]
T = sorted([int(input()) for i in range(N)])
ans = 1
limit = 0
ti = T[0]
for i in range(N - 1):
limit += 1
if ti + K < T[i + 1] or limit == C:
ti = T[i + 1]
ans += 1
limit = 0
print(ans)
``` | output | 1 | 41,945 | 1 | 83,891 |
Provide a correct Python 3 solution for this coding contest problem.
Every day, N passengers arrive at Takahashi Airport. The i-th passenger arrives at time T_i.
Every passenger arrived at Takahashi airport travels to the city by bus. Each bus can accommodate up to C passengers. Naturally, a passenger cannot take a bus that departs earlier than the airplane arrives at the airport. Also, a passenger will get angry if he/she is still unable to take a bus K units of time after the arrival of the airplane. For that reason, it is necessary to arrange buses so that the i-th passenger can take a bus departing at time between T_i and T_i + K (inclusive).
When setting the departure times for buses under this condition, find the minimum required number of buses. Here, the departure time for each bus does not need to be an integer, and there may be multiple buses that depart at the same time.
Constraints
* 2 \leq N \leq 100000
* 1 \leq C \leq 10^9
* 1 \leq K \leq 10^9
* 1 \leq T_i \leq 10^9
* C, K and T_i are integers.
Input
The input is given from Standard Input in the following format:
N C K
T_1
T_2
:
T_N
Output
Print the minimum required number of buses.
Examples
Input
5 3 5
1
2
3
6
12
Output
3
Input
6 3 3
7
6
2
8
10
6
Output
3 | instruction | 0 | 41,946 | 1 | 83,892 |
"Correct Solution:
```
n,c,k = map(int,input().split())
t = list(int(input()) for i in range(n))
t.sort()
ans = 0
x = t[0]
y = 1
for i in range(1,n):
if x+k < t[i] or y >= c:
ans += 1
x = t[i]
y = 1
else:
y += 1
print(ans+1)
``` | output | 1 | 41,946 | 1 | 83,893 |
Provide a correct Python 3 solution for this coding contest problem.
Every day, N passengers arrive at Takahashi Airport. The i-th passenger arrives at time T_i.
Every passenger arrived at Takahashi airport travels to the city by bus. Each bus can accommodate up to C passengers. Naturally, a passenger cannot take a bus that departs earlier than the airplane arrives at the airport. Also, a passenger will get angry if he/she is still unable to take a bus K units of time after the arrival of the airplane. For that reason, it is necessary to arrange buses so that the i-th passenger can take a bus departing at time between T_i and T_i + K (inclusive).
When setting the departure times for buses under this condition, find the minimum required number of buses. Here, the departure time for each bus does not need to be an integer, and there may be multiple buses that depart at the same time.
Constraints
* 2 \leq N \leq 100000
* 1 \leq C \leq 10^9
* 1 \leq K \leq 10^9
* 1 \leq T_i \leq 10^9
* C, K and T_i are integers.
Input
The input is given from Standard Input in the following format:
N C K
T_1
T_2
:
T_N
Output
Print the minimum required number of buses.
Examples
Input
5 3 5
1
2
3
6
12
Output
3
Input
6 3 3
7
6
2
8
10
6
Output
3 | instruction | 0 | 41,947 | 1 | 83,894 |
"Correct Solution:
```
N,C,K = map(int,input().split())
T = [int(input()) for _ in range(N)]
T.sort()
time=T[0]
count = 1
ans = 0
for i in range(1,N):
if T[i]-time>K or count==C:
time = T[i]
count = 1
ans += 1
else:
count += 1
if count>0:
ans += 1
print(ans)
``` | output | 1 | 41,947 | 1 | 83,895 |
Provide a correct Python 3 solution for this coding contest problem.
Every day, N passengers arrive at Takahashi Airport. The i-th passenger arrives at time T_i.
Every passenger arrived at Takahashi airport travels to the city by bus. Each bus can accommodate up to C passengers. Naturally, a passenger cannot take a bus that departs earlier than the airplane arrives at the airport. Also, a passenger will get angry if he/she is still unable to take a bus K units of time after the arrival of the airplane. For that reason, it is necessary to arrange buses so that the i-th passenger can take a bus departing at time between T_i and T_i + K (inclusive).
When setting the departure times for buses under this condition, find the minimum required number of buses. Here, the departure time for each bus does not need to be an integer, and there may be multiple buses that depart at the same time.
Constraints
* 2 \leq N \leq 100000
* 1 \leq C \leq 10^9
* 1 \leq K \leq 10^9
* 1 \leq T_i \leq 10^9
* C, K and T_i are integers.
Input
The input is given from Standard Input in the following format:
N C K
T_1
T_2
:
T_N
Output
Print the minimum required number of buses.
Examples
Input
5 3 5
1
2
3
6
12
Output
3
Input
6 3 3
7
6
2
8
10
6
Output
3 | instruction | 0 | 41,948 | 1 | 83,896 |
"Correct Solution:
```
N,C,K=map(int,input().split())
T=sorted([int(input()) for i in range(N)])
cnt=0
i=0
while(i<N):
j=i
lim=T[i]+K
while(j<N and T[j]<=lim and j-i+1<=C):
j+=1
cnt+=1
i=j
print(cnt)
``` | output | 1 | 41,948 | 1 | 83,897 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Every day, N passengers arrive at Takahashi Airport. The i-th passenger arrives at time T_i.
Every passenger arrived at Takahashi airport travels to the city by bus. Each bus can accommodate up to C passengers. Naturally, a passenger cannot take a bus that departs earlier than the airplane arrives at the airport. Also, a passenger will get angry if he/she is still unable to take a bus K units of time after the arrival of the airplane. For that reason, it is necessary to arrange buses so that the i-th passenger can take a bus departing at time between T_i and T_i + K (inclusive).
When setting the departure times for buses under this condition, find the minimum required number of buses. Here, the departure time for each bus does not need to be an integer, and there may be multiple buses that depart at the same time.
Constraints
* 2 \leq N \leq 100000
* 1 \leq C \leq 10^9
* 1 \leq K \leq 10^9
* 1 \leq T_i \leq 10^9
* C, K and T_i are integers.
Input
The input is given from Standard Input in the following format:
N C K
T_1
T_2
:
T_N
Output
Print the minimum required number of buses.
Examples
Input
5 3 5
1
2
3
6
12
Output
3
Input
6 3 3
7
6
2
8
10
6
Output
3
Submitted Solution:
```
N, C, K = map(int, input().split())
Ts = []
for _ in range(N):
Ts.append(int(input()))
Ts.sort()
cnt = 0
i = 0
while i < N:
j = i
while j < N and Ts[j] <= Ts[i] + K and j - i + 1 <= C:
j += 1
cnt += 1
i = j
print(cnt)
``` | instruction | 0 | 41,949 | 1 | 83,898 |
Yes | output | 1 | 41,949 | 1 | 83,899 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Every day, N passengers arrive at Takahashi Airport. The i-th passenger arrives at time T_i.
Every passenger arrived at Takahashi airport travels to the city by bus. Each bus can accommodate up to C passengers. Naturally, a passenger cannot take a bus that departs earlier than the airplane arrives at the airport. Also, a passenger will get angry if he/she is still unable to take a bus K units of time after the arrival of the airplane. For that reason, it is necessary to arrange buses so that the i-th passenger can take a bus departing at time between T_i and T_i + K (inclusive).
When setting the departure times for buses under this condition, find the minimum required number of buses. Here, the departure time for each bus does not need to be an integer, and there may be multiple buses that depart at the same time.
Constraints
* 2 \leq N \leq 100000
* 1 \leq C \leq 10^9
* 1 \leq K \leq 10^9
* 1 \leq T_i \leq 10^9
* C, K and T_i are integers.
Input
The input is given from Standard Input in the following format:
N C K
T_1
T_2
:
T_N
Output
Print the minimum required number of buses.
Examples
Input
5 3 5
1
2
3
6
12
Output
3
Input
6 3 3
7
6
2
8
10
6
Output
3
Submitted Solution:
```
N, C, K = map(int, input().split())
T = []
for _ in range(N):
T.append(int(input()))
T = sorted(T)
cnt = 0
t = 0
while t < N:
cnt += 1
s = t
while t < N and T[t] - T[s] <= K and t - s < C:
t += 1
print(cnt)
``` | instruction | 0 | 41,950 | 1 | 83,900 |
Yes | output | 1 | 41,950 | 1 | 83,901 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.