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 |
|---|---|---|---|---|---|
Provide tags and a correct Python 3 solution for this coding contest problem.
Woken up by the alarm clock Igor the financial analyst hurried up to the work. He ate his breakfast and sat in his car. Sadly, when he opened his GPS navigator, he found that some of the roads in Bankopolis, the city where he lives, are closed due to road works. Moreover, Igor has some problems with the steering wheel, so he can make no more than two turns on his way to his office in bank.
Bankopolis looks like a grid of n rows and m columns. Igor should find a way from his home to the bank that has no more than two turns and doesn't contain cells with road works, or determine that it is impossible and he should work from home. A turn is a change in movement direction. Igor's car can only move to the left, to the right, upwards and downwards. Initially Igor can choose any direction. Igor is still sleepy, so you should help him.
Input
The first line contains two integers n and m (1 ≤ n, m ≤ 1000) — the number of rows and the number of columns in the grid.
Each of the next n lines contains m characters denoting the corresponding row of the grid. The following characters can occur:
* "." — an empty cell;
* "*" — a cell with road works;
* "S" — the cell where Igor's home is located;
* "T" — the cell where Igor's office is located.
It is guaranteed that "S" and "T" appear exactly once each.
Output
In the only line print "YES" if there is a path between Igor's home and Igor's office with no more than two turns, and "NO" otherwise.
Examples
Input
5 5
..S..
****.
T....
****.
.....
Output
YES
Input
5 5
S....
****.
.....
.****
..T..
Output
NO
Note
The first sample is shown on the following picture:
<image>
In the second sample it is impossible to reach Igor's office using less that 4 turns, thus there exists no path using no more than 2 turns. The path using exactly 4 turns is shown on this picture:
<image> | instruction | 0 | 72,208 | 1 | 144,416 |
Tags: dfs and similar, graphs, implementation, shortest paths
Correct Solution:
```
from typing import List, Set, Dict
def map2home(n: int, m: int, map_in: List[List[str]], turns: int) -> List[list]:
def validate(i, j):
return True if 0 <= i < n and 0 <= j < m and map_in[i][j] != -1 else False
def check(i, j, count):
if end == (i, j):
return 1 if count <= turns else -1
else:
return 0
# mapping
for i in range(n):
for j in range(m):
if map_in[i][j] == "*":
map_in[i][j] = -1
elif map_in[i][j] == ".":
map_in[i][j] = turns + 1
elif map_in[i][j] == "S":
map_in[i][j] = -1
start = i, j
elif map_in[i][j] == "T":
map_in[i][j] = turns + 1
end = i, j
# each element in stack: i, j, dir, and #_of_turns
stack = [(*start, ["left_rt", "up_down"], -1)]
while stack:
temp = []
for curr_i, curr_j, direction, count in stack:
if count == 1:
if curr_i == end[0] and direction == "left_rt":
if curr_j < end[1]:
right = curr_j + 1
while validate(curr_i, right):
if check(curr_i, right, count) == 1:
return "YES"
elif check(curr_i, right, count) == -1:
return "NO"
right += 1
else:
left = curr_j - 1
while validate(curr_i, left):
if check(curr_i, left, count) == 1:
return "YES"
elif check(curr_i, left, count) == -1:
return "NO"
left -= 1
elif curr_j == end[1] and direction == "up_down":
if curr_i < end[0]:
down = curr_i + 1
while validate(down, curr_j):
if check(down, curr_j, count) == 1:
return "YES"
elif check(down, curr_j, count) == -1:
return "NO"
down += 1
else:
up = curr_i - 1
while validate(up, curr_j):
if check(up, curr_j, count) == 1:
return "YES"
elif check(up, curr_j, count) == -1:
return "NO"
up -= 1
else:
if "up_down" in direction:
# up
up = curr_i - 1
while validate(up, curr_j):
map_in[up][curr_j] = count + 1 if count + 1 < map_in[up][curr_j] else map_in[up][curr_j]
temp += [(up, curr_j, "left_rt", count + 1)]
if check(up, curr_j, count ) == 1:
return "YES"
elif check(up, curr_j, count) == -1:
return "NO"
up -= 1
# down
down = curr_i + 1
while validate(down, curr_j):
map_in[down][curr_j] = count + 1 if count + 1 < map_in[down][curr_j] else map_in[down][curr_j]
temp += [(down, curr_j, "left_rt", count + 1)]
if check(down, curr_j, count) == 1:
return "YES"
elif check(down, curr_j, count) == -1:
return "NO"
down += 1
if "left_rt" in direction:
# left
left = curr_j - 1
while validate(curr_i, left):
map_in[curr_i][left] = count + 1 if count + 1 < map_in[curr_i][left] else map_in[curr_i][left]
temp += [(curr_i, left, "up_down", count + 1)]
if check(curr_i, left, count) == 1:
return "YES"
elif check(curr_i, left, count) == -1:
return "NO"
left -= 1
# right
right = curr_j + 1
while validate(curr_i, right):
map_in[curr_i][right] = count + 1 if count + 1 < map_in[curr_i][right] else map_in[curr_i][right]
temp += [(curr_i, right, "up_down", count + 1)]
if check(curr_i, right, count + 1) == 1:
return "YES"
elif check(curr_i, right, count + 1) == -1:
return "NO"
right += 1
stack = temp
return "NO"
if __name__ == "__main__":
n, m = map(int, input().split())
map_ = [list(input()) for _ in range(n)]
result = map2home(n, m, map_, turns=2)
print(result)
``` | output | 1 | 72,208 | 1 | 144,417 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Woken up by the alarm clock Igor the financial analyst hurried up to the work. He ate his breakfast and sat in his car. Sadly, when he opened his GPS navigator, he found that some of the roads in Bankopolis, the city where he lives, are closed due to road works. Moreover, Igor has some problems with the steering wheel, so he can make no more than two turns on his way to his office in bank.
Bankopolis looks like a grid of n rows and m columns. Igor should find a way from his home to the bank that has no more than two turns and doesn't contain cells with road works, or determine that it is impossible and he should work from home. A turn is a change in movement direction. Igor's car can only move to the left, to the right, upwards and downwards. Initially Igor can choose any direction. Igor is still sleepy, so you should help him.
Input
The first line contains two integers n and m (1 ≤ n, m ≤ 1000) — the number of rows and the number of columns in the grid.
Each of the next n lines contains m characters denoting the corresponding row of the grid. The following characters can occur:
* "." — an empty cell;
* "*" — a cell with road works;
* "S" — the cell where Igor's home is located;
* "T" — the cell where Igor's office is located.
It is guaranteed that "S" and "T" appear exactly once each.
Output
In the only line print "YES" if there is a path between Igor's home and Igor's office with no more than two turns, and "NO" otherwise.
Examples
Input
5 5
..S..
****.
T....
****.
.....
Output
YES
Input
5 5
S....
****.
.....
.****
..T..
Output
NO
Note
The first sample is shown on the following picture:
<image>
In the second sample it is impossible to reach Igor's office using less that 4 turns, thus there exists no path using no more than 2 turns. The path using exactly 4 turns is shown on this picture:
<image>
Submitted Solution:
```
import sys
from collections import deque
def main():
n,m=map(int,sys.stdin.readline().split())
field=[]
for _ in range(n):
field.append(list(sys.stdin.readline().rstrip()))
istart,jstart=[(i,j) for i in range(n) for j in range(m) if field[i][j]=='S'][0]
iend,jend=[(i,j) for i in range(n) for j in range(m) if field[i][j]=='T'][0]
result='NO'
#hor+ver+hor
jstart1=jstart-1
while jstart1>=0:
if field[istart][jstart1]=='*': break
jstart1-=1
jstart1+=1
jstart2=jstart+1
while jstart2<m:
if field[istart][jstart2]=='*': break
jstart2+=1
jstart2-=1
jend1=jend-1
while jend1>=0:
if field[iend][jend1]=='*': break
jend1-=1
jend1+=1
jend2=jend+1
while jend2<m:
if field[iend][jend2]=='*': break
jend2+=1
jend2-=1
for j in range(max(jstart1,jend1),min(jstart2,jend2)+1):
if all(field[i][j]!='*' for i in range(min(istart,iend),max(istart,iend)+1)):
result='YES'
sys.stdout.write(result+'\n')
return
#ver+hor+ver
istart1=istart-1
while istart1>=0:
if field[istart1][jstart]=='*': break
istart1-=1
istart1+=1
istart2=istart+1
while istart2<n:
if field[istart2][jstart]=='*': break
istart2+=1
istart2-=1
iend1=iend-1
while iend1>=0:
if field[iend1][jend]=='*': break
iend1-=1
iend1+=1
iend2=iend+1
while iend2<n:
if field[iend2][jend]=='*': break
iend2+=1
iend2-=1
for i in range(max(istart1,iend1),min(istart2,iend2)+1):
if all(field[i][j]!='*' for j in range(min(jstart,jend),max(jstart,jend)+1)):
result='YES'
sys.stdout.write(result+'\n')
return
sys.stdout.write(result+'\n')
main()
``` | instruction | 0 | 72,209 | 1 | 144,418 |
Yes | output | 1 | 72,209 | 1 | 144,419 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Woken up by the alarm clock Igor the financial analyst hurried up to the work. He ate his breakfast and sat in his car. Sadly, when he opened his GPS navigator, he found that some of the roads in Bankopolis, the city where he lives, are closed due to road works. Moreover, Igor has some problems with the steering wheel, so he can make no more than two turns on his way to his office in bank.
Bankopolis looks like a grid of n rows and m columns. Igor should find a way from his home to the bank that has no more than two turns and doesn't contain cells with road works, or determine that it is impossible and he should work from home. A turn is a change in movement direction. Igor's car can only move to the left, to the right, upwards and downwards. Initially Igor can choose any direction. Igor is still sleepy, so you should help him.
Input
The first line contains two integers n and m (1 ≤ n, m ≤ 1000) — the number of rows and the number of columns in the grid.
Each of the next n lines contains m characters denoting the corresponding row of the grid. The following characters can occur:
* "." — an empty cell;
* "*" — a cell with road works;
* "S" — the cell where Igor's home is located;
* "T" — the cell where Igor's office is located.
It is guaranteed that "S" and "T" appear exactly once each.
Output
In the only line print "YES" if there is a path between Igor's home and Igor's office with no more than two turns, and "NO" otherwise.
Examples
Input
5 5
..S..
****.
T....
****.
.....
Output
YES
Input
5 5
S....
****.
.....
.****
..T..
Output
NO
Note
The first sample is shown on the following picture:
<image>
In the second sample it is impossible to reach Igor's office using less that 4 turns, thus there exists no path using no more than 2 turns. The path using exactly 4 turns is shown on this picture:
<image>
Submitted Solution:
```
import sys
from collections import deque
def is_valid(r, c, n, m):
return 0 <= r < n and 0 <= c < m
def get_neighbors(cid, dir, n, m):
update_c = [1, 0, -1, 0]
update_r = [0, -1, 0, 1]
neighbors = []
r = cid // m
c = cid % m
for j in [0, -1, 1]:
cost = 1 if j != 0 else 0
d = (dir + j + 4) % 4
nc = c + update_c[d]
nr = r + update_r[d]
if is_valid(nr, nc, n, m):
nid = nr * m + nc
neighbors.append((nid, cost, d))
return neighbors
def add_to_queue(cid, from_dir, cost, to_visit, blocked, n_turns):
if not blocked[cid]:
if n_turns[cid][from_dir] == 1000 * 1000 + 1:
to_visit.append((cid, from_dir))
n_turns[cid][from_dir] = cost
elif n_turns[cid][from_dir] > cost:
n_turns[cid][from_dir] = cost
def solve(start, end, blocked, n, m):
if start == end:
return True
inf = 1000 * 1000 + 1
# n_turns: minimum number of turn to get there from each direction
n_turns = [[inf, inf, inf, inf] for _ in range(n * m)]
n_turns[start] = [0, 0, 0, 0]
to_visit = deque()
to_visit.append((start, 0))
to_visit.append((start, 1))
to_visit.append((start, 2))
to_visit.append((start, 3))
while to_visit:
(cid, dir) = to_visit.popleft()
if cid == end and n_turns[cid][dir] <= 2:
return True
for nid, cost, new_dir in get_neighbors(cid, dir, n, m):
add_to_queue(nid, new_dir, n_turns[cid][dir] + cost, to_visit, blocked, n_turns)
return False
# Parse inputs
n, m = map(int, next(sys.stdin).strip().split())
cid = 0
start, end = -1, -1
blocked = [False for i in range(n * m)]
for line in sys.stdin:
cells = line.strip()
for cell in cells:
if cell == 'S':
start = cid
elif cell == 'T':
end = cid
elif cell == '*':
blocked[cid] = True
cid += 1
ans = solve(start, end, blocked, n, m)
# Print output
sys.stdout.write("{}\n".format("YES" if ans else "NO"))
``` | instruction | 0 | 72,210 | 1 | 144,420 |
Yes | output | 1 | 72,210 | 1 | 144,421 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Woken up by the alarm clock Igor the financial analyst hurried up to the work. He ate his breakfast and sat in his car. Sadly, when he opened his GPS navigator, he found that some of the roads in Bankopolis, the city where he lives, are closed due to road works. Moreover, Igor has some problems with the steering wheel, so he can make no more than two turns on his way to his office in bank.
Bankopolis looks like a grid of n rows and m columns. Igor should find a way from his home to the bank that has no more than two turns and doesn't contain cells with road works, or determine that it is impossible and he should work from home. A turn is a change in movement direction. Igor's car can only move to the left, to the right, upwards and downwards. Initially Igor can choose any direction. Igor is still sleepy, so you should help him.
Input
The first line contains two integers n and m (1 ≤ n, m ≤ 1000) — the number of rows and the number of columns in the grid.
Each of the next n lines contains m characters denoting the corresponding row of the grid. The following characters can occur:
* "." — an empty cell;
* "*" — a cell with road works;
* "S" — the cell where Igor's home is located;
* "T" — the cell where Igor's office is located.
It is guaranteed that "S" and "T" appear exactly once each.
Output
In the only line print "YES" if there is a path between Igor's home and Igor's office with no more than two turns, and "NO" otherwise.
Examples
Input
5 5
..S..
****.
T....
****.
.....
Output
YES
Input
5 5
S....
****.
.....
.****
..T..
Output
NO
Note
The first sample is shown on the following picture:
<image>
In the second sample it is impossible to reach Igor's office using less that 4 turns, thus there exists no path using no more than 2 turns. The path using exactly 4 turns is shown on this picture:
<image>
Submitted Solution:
```
n, m = map(int, input().split())
a = []
x, y = 0, 0
def f(c, x, y):
for i in range(x + 1, n):
if a[i][y] == 'T':
print('YES')
exit()
if a[i][y] == '.':
a[i][y] = c
elif a[i][y] != c:
break
for i in range(x - 1, -1, -1):
if a[i][y] == 'T':
print('YES')
exit()
if a[i][y] == '.':
a[i][y] = c
elif a[i][y] != c:
break
for j in range(y + 1, m):
if a[x][j] == 'T':
print('YES')
exit()
if a[x][j] == '.':
a[x][j] = c
elif a[x][j] != c:
break
for j in range(y - 1, -1, -1):
if a[x][j] == 'T':
print('YES')
exit()
if a[x][j] == '.':
a[x][j] = c
elif a[x][j] != c:
break
for i in range(n):
s = input()
for j in range(m):
if s[j] == 'S':
x, y = i, j
a.append(list(s))
f('1', x, y)
for i in range(n):
for j in range(m):
if a[i][j] == '1':
f('2', i, j)
for i in range(n):
for j in range(m):
if a[i][j] == '2':
f('3', i, j)
print('NO')
``` | instruction | 0 | 72,211 | 1 | 144,422 |
Yes | output | 1 | 72,211 | 1 | 144,423 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Woken up by the alarm clock Igor the financial analyst hurried up to the work. He ate his breakfast and sat in his car. Sadly, when he opened his GPS navigator, he found that some of the roads in Bankopolis, the city where he lives, are closed due to road works. Moreover, Igor has some problems with the steering wheel, so he can make no more than two turns on his way to his office in bank.
Bankopolis looks like a grid of n rows and m columns. Igor should find a way from his home to the bank that has no more than two turns and doesn't contain cells with road works, or determine that it is impossible and he should work from home. A turn is a change in movement direction. Igor's car can only move to the left, to the right, upwards and downwards. Initially Igor can choose any direction. Igor is still sleepy, so you should help him.
Input
The first line contains two integers n and m (1 ≤ n, m ≤ 1000) — the number of rows and the number of columns in the grid.
Each of the next n lines contains m characters denoting the corresponding row of the grid. The following characters can occur:
* "." — an empty cell;
* "*" — a cell with road works;
* "S" — the cell where Igor's home is located;
* "T" — the cell where Igor's office is located.
It is guaranteed that "S" and "T" appear exactly once each.
Output
In the only line print "YES" if there is a path between Igor's home and Igor's office with no more than two turns, and "NO" otherwise.
Examples
Input
5 5
..S..
****.
T....
****.
.....
Output
YES
Input
5 5
S....
****.
.....
.****
..T..
Output
NO
Note
The first sample is shown on the following picture:
<image>
In the second sample it is impossible to reach Igor's office using less that 4 turns, thus there exists no path using no more than 2 turns. The path using exactly 4 turns is shown on this picture:
<image>
Submitted Solution:
```
n, m = map(int, input().split())
a = [input() for _ in range(n)]
s = t = None
for i in range(n):
for j in range(m):
if a[i][j] == 'S':
s = (i, j)
elif a[i][j] == 'T':
t = (i, j)
row_cnt = [[0] * (m + 1) for _ in range(n)]
col_cnt = [[0] * (n + 1) for _ in range(m)]
for i in range(n):
for j in range(m):
row_cnt[i][j + 1] = row_cnt[i][j] + (a[i][j] == '*')
col_cnt[j][i + 1] = col_cnt[j][i] + (a[i][j] == '*')
def row_free(i, j, k):
if j > k: j, k = k, j
return row_cnt[i][k + 1] - row_cnt[i][j] == 0
def col_free(i, j, k):
if j > k: j, k = k, j
return col_cnt[i][k + 1] - col_cnt[i][j] == 0
if s[1] > t[1]:
s, t = t, s
ans = 'NO'
for i in range(n):
if col_free(s[1], i, s[0]) and col_free(t[1], i, t[0]) and row_free(i, s[1], t[1]):
ans = 'YES'
break
if ans == 'NO':
if s[0] > t[0]:
s, t = t, s
for j in range(m):
if row_free(s[0], j, s[1]) and row_free(t[0], j, t[1]) and col_free(j, s[0], t[0]):
ans = 'YES'
break
print(ans)
``` | instruction | 0 | 72,212 | 1 | 144,424 |
Yes | output | 1 | 72,212 | 1 | 144,425 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Woken up by the alarm clock Igor the financial analyst hurried up to the work. He ate his breakfast and sat in his car. Sadly, when he opened his GPS navigator, he found that some of the roads in Bankopolis, the city where he lives, are closed due to road works. Moreover, Igor has some problems with the steering wheel, so he can make no more than two turns on his way to his office in bank.
Bankopolis looks like a grid of n rows and m columns. Igor should find a way from his home to the bank that has no more than two turns and doesn't contain cells with road works, or determine that it is impossible and he should work from home. A turn is a change in movement direction. Igor's car can only move to the left, to the right, upwards and downwards. Initially Igor can choose any direction. Igor is still sleepy, so you should help him.
Input
The first line contains two integers n and m (1 ≤ n, m ≤ 1000) — the number of rows and the number of columns in the grid.
Each of the next n lines contains m characters denoting the corresponding row of the grid. The following characters can occur:
* "." — an empty cell;
* "*" — a cell with road works;
* "S" — the cell where Igor's home is located;
* "T" — the cell where Igor's office is located.
It is guaranteed that "S" and "T" appear exactly once each.
Output
In the only line print "YES" if there is a path between Igor's home and Igor's office with no more than two turns, and "NO" otherwise.
Examples
Input
5 5
..S..
****.
T....
****.
.....
Output
YES
Input
5 5
S....
****.
.....
.****
..T..
Output
NO
Note
The first sample is shown on the following picture:
<image>
In the second sample it is impossible to reach Igor's office using less that 4 turns, thus there exists no path using no more than 2 turns. The path using exactly 4 turns is shown on this picture:
<image>
Submitted Solution:
```
from collections import deque as dq
st=0
class Graph:
def __init__(self,n=0,m=0):
self.g=[None for i in range(n)]
self.vis=[[False for j in range(m)] for i in range(n)]
self.dx=(1,0,-1,0)
self.dy=(0,1,0,-1)
self.p=[[10**10 for i in range(m)] for j in range(n)]
def affiche(self):
for i in range(len(self.g)):
print("".join(self.g[i]))
def readG(self,n):
for i in range(n):
self.g[i]=list(input())
def get(self,i,j):
return self.g[i][j]
def dfsIt(self,u):
global k,A
L=dq()
A=[]
u.append(0)
L.append(u)
u=L[-1]#.pop()
self.p[u[0]][u[1]]=0
L.pop()
self.vis[u[0]][u[1]]=True
a=self.p[u[0]][u[1]]+1
for t in range(4):
x=u[0]+self.dx[t]
y=u[1]+self.dy[t]
if x>=0 and x<n and y>=0 and y<m and self.g[x][y]!='*':
if a<self.p[x][y]:
self.p[x][y]=a
else:
continue
L.append([u,(x,y,u[2])])
if self.g[x][y]=='T':
return "YES"
while len(L)!=0:
#print(L)
x=L.pop()
pp=x[0]
p=x[1]
#print(self.p[p[0]][p[1]])
#input()
self.vis[p[0]][p[1]]=True
if p[2]>2:
continue
for t in range(4):
x=p[0]+self.dx[t]
y=p[1]+self.dy[t]
if x>=0 and x<n and y>=0 and y<m and self.g[x][y]!='*':
if (x==p[0] and x==pp[0]) or (y==p[1] and y==pp[1]):
a=self.p[p[0]][p[1]]
else:
a=self.p[p[0]][p[1]]+1
if a<self.p[x][y]:
self.p[x][y]=a
else:
continue
if self.g[x][y]=='T':
return "YES"
if (x==p[0] and x==pp[0]) or (y==p[1] and y==pp[1]):
L.append([p,(x,y,p[2])])
else:
L.append([p,(x,y,p[2]+1)])
return "NO"
n,m=map(int,input().split())
g=Graph(n,m)
g.readG(n)
def f():
global n,m,g,st
b=0
for i in range(n):
for j in range(m):
if g.get(i,j)=='S':
st=[i,j]
return
f()
print(g.dfsIt(st))
``` | instruction | 0 | 72,213 | 1 | 144,426 |
No | output | 1 | 72,213 | 1 | 144,427 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Woken up by the alarm clock Igor the financial analyst hurried up to the work. He ate his breakfast and sat in his car. Sadly, when he opened his GPS navigator, he found that some of the roads in Bankopolis, the city where he lives, are closed due to road works. Moreover, Igor has some problems with the steering wheel, so he can make no more than two turns on his way to his office in bank.
Bankopolis looks like a grid of n rows and m columns. Igor should find a way from his home to the bank that has no more than two turns and doesn't contain cells with road works, or determine that it is impossible and he should work from home. A turn is a change in movement direction. Igor's car can only move to the left, to the right, upwards and downwards. Initially Igor can choose any direction. Igor is still sleepy, so you should help him.
Input
The first line contains two integers n and m (1 ≤ n, m ≤ 1000) — the number of rows and the number of columns in the grid.
Each of the next n lines contains m characters denoting the corresponding row of the grid. The following characters can occur:
* "." — an empty cell;
* "*" — a cell with road works;
* "S" — the cell where Igor's home is located;
* "T" — the cell where Igor's office is located.
It is guaranteed that "S" and "T" appear exactly once each.
Output
In the only line print "YES" if there is a path between Igor's home and Igor's office with no more than two turns, and "NO" otherwise.
Examples
Input
5 5
..S..
****.
T....
****.
.....
Output
YES
Input
5 5
S....
****.
.....
.****
..T..
Output
NO
Note
The first sample is shown on the following picture:
<image>
In the second sample it is impossible to reach Igor's office using less that 4 turns, thus there exists no path using no more than 2 turns. The path using exactly 4 turns is shown on this picture:
<image>
Submitted Solution:
```
from collections import deque as dq
st=0
end=0
class Graph:
def __init__(self,n=0,m=0):
self.g=[None for i in range(n)]
self.vis=[[False for j in range(m)] for i in range(n)]
self.dx=(1,0,-1,0)
self.dy=(0,1,0,-1)
def affiche(self):
for i in range(len(self.g)):
print("".join(self.g[i]))
def readG(self,n):
for i in range(n):
self.g[i]=list(input())
def get(self,i,j):
return self.g[i][j]
def dfsIt(self,u):
global k,A
L=dq()
A=[]
u.append(0)
L.append(u)
u=L[-1]#.pop()
L.pop()
self.vis[u[0]][u[1]]=True
for t in range(4):
x=u[0]+self.dx[t]
y=u[1]+self.dy[t]
if x==end[0] and y==end[1]:
return "YES"
if x>=0 and x<n and y>=0 and y<m and not self.vis[x][y] and self.g[x][y]!='*':
L.append([u,(x,y,u[2])])
while len(L)!=0:
x=L.pop()
pp=x[0]
p=x[1]
self.vis[p[0]][p[1]]=True
if p[2]>=2:
break
for t in range(4):
x=p[0]+self.dx[t]
y=p[1]+self.dy[t]
if x==end[0] and y==end[1]:
return "YES"
if x>=0 and x<n and y>=0 and y<m and not self.vis[x][y] and self.g[x][y]!='*':
if x==p[0]==pp[0] or y==p[1]==pp[1]:
L.append([p,(x,y,p[2])])
else:
L.append([p,(x,y,p[2]+1)])
return "NO"
n,m=map(int,input().split())
g=Graph(n,m)
g.readG(n)
def f():
global n,m,g,st,end
b=0
for i in range(n):
for j in range(m):
if g.get(i,j)=='S':
b+=1
st=[i,j]
elif g.get(i,j)=='T':
b+=1
end=[i,j]
if b==2:
return
f()
print(g.dfsIt(st))
``` | instruction | 0 | 72,214 | 1 | 144,428 |
No | output | 1 | 72,214 | 1 | 144,429 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Woken up by the alarm clock Igor the financial analyst hurried up to the work. He ate his breakfast and sat in his car. Sadly, when he opened his GPS navigator, he found that some of the roads in Bankopolis, the city where he lives, are closed due to road works. Moreover, Igor has some problems with the steering wheel, so he can make no more than two turns on his way to his office in bank.
Bankopolis looks like a grid of n rows and m columns. Igor should find a way from his home to the bank that has no more than two turns and doesn't contain cells with road works, or determine that it is impossible and he should work from home. A turn is a change in movement direction. Igor's car can only move to the left, to the right, upwards and downwards. Initially Igor can choose any direction. Igor is still sleepy, so you should help him.
Input
The first line contains two integers n and m (1 ≤ n, m ≤ 1000) — the number of rows and the number of columns in the grid.
Each of the next n lines contains m characters denoting the corresponding row of the grid. The following characters can occur:
* "." — an empty cell;
* "*" — a cell with road works;
* "S" — the cell where Igor's home is located;
* "T" — the cell where Igor's office is located.
It is guaranteed that "S" and "T" appear exactly once each.
Output
In the only line print "YES" if there is a path between Igor's home and Igor's office with no more than two turns, and "NO" otherwise.
Examples
Input
5 5
..S..
****.
T....
****.
.....
Output
YES
Input
5 5
S....
****.
.....
.****
..T..
Output
NO
Note
The first sample is shown on the following picture:
<image>
In the second sample it is impossible to reach Igor's office using less that 4 turns, thus there exists no path using no more than 2 turns. The path using exactly 4 turns is shown on this picture:
<image>
Submitted Solution:
```
n, m = map(int, input().split())
data = [list(input().strip()) for i in range(n)]
for i, v in enumerate(data):
if "S" in v:
si = i
sk = v.index("S")
break
for i, v in enumerate(data):
if "T" in v:
ti = i
tk = v.index("T")
break
yes = False
for i in range(ti, -1 -1):
if data[i][tk] == 'S':
yes = True
break
elif data[i][tk] == '*':
break
else:
data[i][tk] = '0'
for i in range(ti, n):
if data[i][tk] == 'S':
yes = True
break
elif data[i][tk] == '*':
break
else:
data[i][tk] = '0'
for k in range(tk, -1 -1):
if data[ti][k] == 'S':
yes = True
break
elif data[ti][k] == '*':
break
else:
data[ti][k] = '0'
for k in range(tk, m):
if data[ti][k] == 'S':
yes = True
break
elif data[ti][k] == '*':
break
else:
data[ti][k] = '0'
if not yes:
for i in range(si, -1 -1):
if data[i][sk] == 'T':
yes = True
break
elif data[i][sk] == '0':
yes = True
break
elif data[i][sk] == '*':
break
else:
for k in range(sk, -1 -1):
if data[i][k] == 'T':
yes = True
break
elif data[i][k] == '0':
yes = True
break
elif data[i][k] == '*':
break
for k in range(sk, m):
if data[i][k] == 'T':
yes = True
break
elif data[i][k] == '0':
yes = True
break
elif data[i][k] == '*':
break
if not yes:
for i in range(si, n):
if data[i][sk] == 'T':
yes = True
break
elif data[i][sk] == '0':
yes = True
break
elif data[i][sk] == '*':
break
else:
for k in range(sk, -1 -1):
if data[i][k] == 'T':
yes = True
break
elif data[i][k] == '0':
yes = True
break
elif data[i][k] == '*':
break
for k in range(sk, m):
if data[i][k] == 'T':
yes = True
break
elif data[i][k] == '0':
yes = True
break
elif data[i][k] == '*':
break
if not yes:
for k in range(sk, -1 -1):
if data[si][k] == 'T':
yes = True
break
elif data[si][k] == '0':
yes = True
break
elif data[si][k] == '*':
break
else:
for i in range(si, -1 -1):
if data[i][k] == 'T':
yes = True
break
elif data[i][k] == '0':
yes = True
break
elif data[i][k] == '*':
break
for i in range(si, n):
if data[i][k] == 'T':
yes = True
break
elif data[i][k] == '0':
yes = True
break
elif data[i][k] == '*':
break
if not yes:
for k in range(sk, m):
if data[si][k] == 'T':
yes = True
break
elif data[si][k] == '0':
yes = True
break
elif data[si][k] == '*':
break
else:
for i in range(si, -1 -1):
if data[i][k] == 'T':
yes = True
break
elif data[i][k] == '0':
yes = True
break
elif data[i][k] == '*':
break
for i in range(si, n):
if data[i][k] == 'T':
yes = True
break
elif data[i][k] == '0':
yes = True
break
elif data[i][k] == '*':
break
if yes:
print("YES")
else:
print("NO")
``` | instruction | 0 | 72,215 | 1 | 144,430 |
No | output | 1 | 72,215 | 1 | 144,431 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Woken up by the alarm clock Igor the financial analyst hurried up to the work. He ate his breakfast and sat in his car. Sadly, when he opened his GPS navigator, he found that some of the roads in Bankopolis, the city where he lives, are closed due to road works. Moreover, Igor has some problems with the steering wheel, so he can make no more than two turns on his way to his office in bank.
Bankopolis looks like a grid of n rows and m columns. Igor should find a way from his home to the bank that has no more than two turns and doesn't contain cells with road works, or determine that it is impossible and he should work from home. A turn is a change in movement direction. Igor's car can only move to the left, to the right, upwards and downwards. Initially Igor can choose any direction. Igor is still sleepy, so you should help him.
Input
The first line contains two integers n and m (1 ≤ n, m ≤ 1000) — the number of rows and the number of columns in the grid.
Each of the next n lines contains m characters denoting the corresponding row of the grid. The following characters can occur:
* "." — an empty cell;
* "*" — a cell with road works;
* "S" — the cell where Igor's home is located;
* "T" — the cell where Igor's office is located.
It is guaranteed that "S" and "T" appear exactly once each.
Output
In the only line print "YES" if there is a path between Igor's home and Igor's office with no more than two turns, and "NO" otherwise.
Examples
Input
5 5
..S..
****.
T....
****.
.....
Output
YES
Input
5 5
S....
****.
.....
.****
..T..
Output
NO
Note
The first sample is shown on the following picture:
<image>
In the second sample it is impossible to reach Igor's office using less that 4 turns, thus there exists no path using no more than 2 turns. The path using exactly 4 turns is shown on this picture:
<image>
Submitted Solution:
```
from collections import deque as dq
st=0
end=0
class Graph:
def __init__(self,n=0,m=0):
self.g=[None for i in range(n)]
self.vis=[[False for j in range(m)] for i in range(n)]
self.dx=(1,0,-1,0)
self.dy=(0,1,0,-1)
def affiche(self):
for i in range(len(self.g)):
print("".join(self.g[i]))
def readG(self,n):
for i in range(n):
self.g[i]=list(input())
def get(self,i,j):
return self.g[i][j]
def dfsIt(self,u):
global k,A
L=dq()
A=[]
u.append(0)
L.append(u)
u=L[-1]#.pop()
L.pop()
self.vis[u[0]][u[1]]=True
for t in range(4):
x=u[0]+self.dx[t]
y=u[1]+self.dy[t]
if x==end[0] and y==end[1]:
return "YES"
if x>=0 and x<n and y>=0 and y<m and not self.vis[x][y] and self.g[x][y]!='*':
L.append([u,(x,y,u[2])])
while len(L)!=0:
x=L.pop()
pp=x[0]
p=x[1]
self.vis[p[0]][p[1]]=True
if p[2]>2:
continue
if p[0]==end[0] and p[1]==end[1]:
return "YES"
for t in range(4):
x=p[0]+self.dx[t]
y=p[1]+self.dy[t]
if x>=0 and x<n and y>=0 and y<m and not self.vis[x][y] and self.g[x][y]!='*':
if x==p[0]==pp[0] or y==p[1]==pp[1]:
L.append([p,(x,y,p[2])])
else:
L.append([p,(x,y,p[2]+1)])
return "NO"
n,m=map(int,input().split())
g=Graph(n,m)
g.readG(n)
def f():
global n,m,g,st,end
b=0
for i in range(n):
for j in range(m):
if g.get(i,j)=='S':
b+=1
st=[i,j]
elif g.get(i,j)=='T':
b+=1
end=[i,j]
if b==2:
return
f()
print(g.dfsIt(st))
``` | instruction | 0 | 72,216 | 1 | 144,432 |
No | output | 1 | 72,216 | 1 | 144,433 |
Provide a correct Python 3 solution for this coding contest problem.
There are N sightseeing spots on the x-axis, numbered 1, 2, ..., N. Spot i is at the point with coordinate A_i. It costs |a - b| yen (the currency of Japan) to travel from a point with coordinate a to another point with coordinate b along the axis.
You planned a trip along the axis. In this plan, you first depart from the point with coordinate 0, then visit the N spots in the order they are numbered, and finally return to the point with coordinate 0.
However, something came up just before the trip, and you no longer have enough time to visit all the N spots, so you decided to choose some i and cancel the visit to Spot i. You will visit the remaining spots as planned in the order they are numbered. You will also depart from and return to the point with coordinate 0 at the beginning and the end, as planned.
For each i = 1, 2, ..., N, find the total cost of travel during the trip when the visit to Spot i is canceled.
Constraints
* 2 \leq N \leq 10^5
* -5000 \leq A_i \leq 5000 (1 \leq i \leq N)
* All input values are integers.
Input
Input is given from Standard Input in the following format:
N
A_1 A_2 ... A_N
Output
Print N lines. In the i-th line, print the total cost of travel during the trip when the visit to Spot i is canceled.
Examples
Input
3
3 5 -1
Output
12
8
10
Input
5
1 1 1 2 0
Output
4
4
4
2
4
Input
6
-679 -2409 -3258 3095 -3291 -4462
Output
21630
21630
19932
8924
21630
19288 | instruction | 0 | 72,352 | 1 | 144,704 |
"Correct Solution:
```
N = int(input())
a = list(map(int,input().split(" ")))
a.append(0)
a.insert(0,0)
dis = 0
for i in range(N+1):
dis += (abs(a[i+1] - a[i]))
for i in range(N):
ans = dis - abs(a[i+1] - a[i]) - abs(a[i+2] - a[i+1]) + abs(a[i+2] - a[i])
print(ans)
``` | output | 1 | 72,352 | 1 | 144,705 |
Provide a correct Python 3 solution for this coding contest problem.
There are N sightseeing spots on the x-axis, numbered 1, 2, ..., N. Spot i is at the point with coordinate A_i. It costs |a - b| yen (the currency of Japan) to travel from a point with coordinate a to another point with coordinate b along the axis.
You planned a trip along the axis. In this plan, you first depart from the point with coordinate 0, then visit the N spots in the order they are numbered, and finally return to the point with coordinate 0.
However, something came up just before the trip, and you no longer have enough time to visit all the N spots, so you decided to choose some i and cancel the visit to Spot i. You will visit the remaining spots as planned in the order they are numbered. You will also depart from and return to the point with coordinate 0 at the beginning and the end, as planned.
For each i = 1, 2, ..., N, find the total cost of travel during the trip when the visit to Spot i is canceled.
Constraints
* 2 \leq N \leq 10^5
* -5000 \leq A_i \leq 5000 (1 \leq i \leq N)
* All input values are integers.
Input
Input is given from Standard Input in the following format:
N
A_1 A_2 ... A_N
Output
Print N lines. In the i-th line, print the total cost of travel during the trip when the visit to Spot i is canceled.
Examples
Input
3
3 5 -1
Output
12
8
10
Input
5
1 1 1 2 0
Output
4
4
4
2
4
Input
6
-679 -2409 -3258 3095 -3291 -4462
Output
21630
21630
19932
8924
21630
19288 | instruction | 0 | 72,353 | 1 | 144,706 |
"Correct Solution:
```
n=int(input())
a=list(map(int,input().split()))
cs=abs(a[0])
a.append(0)
for i in range(n):
cs+=abs(a[i]-a[i+1])
print(cs-abs(a[0])-abs(a[0]-a[1])+abs(a[1]))
for i in range(1,n):
print(cs-abs(a[i-1]-a[i])-abs(a[i]-a[i+1])+abs(a[i-1]-a[i+1]))
``` | output | 1 | 72,353 | 1 | 144,707 |
Provide a correct Python 3 solution for this coding contest problem.
There are N sightseeing spots on the x-axis, numbered 1, 2, ..., N. Spot i is at the point with coordinate A_i. It costs |a - b| yen (the currency of Japan) to travel from a point with coordinate a to another point with coordinate b along the axis.
You planned a trip along the axis. In this plan, you first depart from the point with coordinate 0, then visit the N spots in the order they are numbered, and finally return to the point with coordinate 0.
However, something came up just before the trip, and you no longer have enough time to visit all the N spots, so you decided to choose some i and cancel the visit to Spot i. You will visit the remaining spots as planned in the order they are numbered. You will also depart from and return to the point with coordinate 0 at the beginning and the end, as planned.
For each i = 1, 2, ..., N, find the total cost of travel during the trip when the visit to Spot i is canceled.
Constraints
* 2 \leq N \leq 10^5
* -5000 \leq A_i \leq 5000 (1 \leq i \leq N)
* All input values are integers.
Input
Input is given from Standard Input in the following format:
N
A_1 A_2 ... A_N
Output
Print N lines. In the i-th line, print the total cost of travel during the trip when the visit to Spot i is canceled.
Examples
Input
3
3 5 -1
Output
12
8
10
Input
5
1 1 1 2 0
Output
4
4
4
2
4
Input
6
-679 -2409 -3258 3095 -3291 -4462
Output
21630
21630
19932
8924
21630
19288 | instruction | 0 | 72,354 | 1 | 144,708 |
"Correct Solution:
```
n = int(input())
ai = list(map(int,input().split()))
a = [0]
for i in ai:
a.append(i)
al = [0] * (n+1)
for i in range(n+1):
al[i] = abs(a[(i+1)%(n+1)] - a[i])
s = sum(al)
for i in range(1,n+1):
print(s-al[i-1]-al[i]+abs(a[(i+1)%(n+1)]-a[i-1]))
``` | output | 1 | 72,354 | 1 | 144,709 |
Provide a correct Python 3 solution for this coding contest problem.
There are N sightseeing spots on the x-axis, numbered 1, 2, ..., N. Spot i is at the point with coordinate A_i. It costs |a - b| yen (the currency of Japan) to travel from a point with coordinate a to another point with coordinate b along the axis.
You planned a trip along the axis. In this plan, you first depart from the point with coordinate 0, then visit the N spots in the order they are numbered, and finally return to the point with coordinate 0.
However, something came up just before the trip, and you no longer have enough time to visit all the N spots, so you decided to choose some i and cancel the visit to Spot i. You will visit the remaining spots as planned in the order they are numbered. You will also depart from and return to the point with coordinate 0 at the beginning and the end, as planned.
For each i = 1, 2, ..., N, find the total cost of travel during the trip when the visit to Spot i is canceled.
Constraints
* 2 \leq N \leq 10^5
* -5000 \leq A_i \leq 5000 (1 \leq i \leq N)
* All input values are integers.
Input
Input is given from Standard Input in the following format:
N
A_1 A_2 ... A_N
Output
Print N lines. In the i-th line, print the total cost of travel during the trip when the visit to Spot i is canceled.
Examples
Input
3
3 5 -1
Output
12
8
10
Input
5
1 1 1 2 0
Output
4
4
4
2
4
Input
6
-679 -2409 -3258 3095 -3291 -4462
Output
21630
21630
19932
8924
21630
19288 | instruction | 0 | 72,355 | 1 | 144,710 |
"Correct Solution:
```
def i1():
return int(input())
def i2():
return [int(i) for i in input().split()]
n=i1()
a=[0]+i2()+[0]
b=[]
c=0
d=[]
for i in range(n+1):
b.append(abs(a[i]-a[i+1]))
c+=b[-1]
if i<n:d.append(abs(a[i]-a[i+2]))
for i in range(n):
print(c-b[i]-b[i+1]+d[i])
``` | output | 1 | 72,355 | 1 | 144,711 |
Provide a correct Python 3 solution for this coding contest problem.
There are N sightseeing spots on the x-axis, numbered 1, 2, ..., N. Spot i is at the point with coordinate A_i. It costs |a - b| yen (the currency of Japan) to travel from a point with coordinate a to another point with coordinate b along the axis.
You planned a trip along the axis. In this plan, you first depart from the point with coordinate 0, then visit the N spots in the order they are numbered, and finally return to the point with coordinate 0.
However, something came up just before the trip, and you no longer have enough time to visit all the N spots, so you decided to choose some i and cancel the visit to Spot i. You will visit the remaining spots as planned in the order they are numbered. You will also depart from and return to the point with coordinate 0 at the beginning and the end, as planned.
For each i = 1, 2, ..., N, find the total cost of travel during the trip when the visit to Spot i is canceled.
Constraints
* 2 \leq N \leq 10^5
* -5000 \leq A_i \leq 5000 (1 \leq i \leq N)
* All input values are integers.
Input
Input is given from Standard Input in the following format:
N
A_1 A_2 ... A_N
Output
Print N lines. In the i-th line, print the total cost of travel during the trip when the visit to Spot i is canceled.
Examples
Input
3
3 5 -1
Output
12
8
10
Input
5
1 1 1 2 0
Output
4
4
4
2
4
Input
6
-679 -2409 -3258 3095 -3291 -4462
Output
21630
21630
19932
8924
21630
19288 | instruction | 0 | 72,356 | 1 | 144,712 |
"Correct Solution:
```
N = int(input())
A = list(map(int, input().split()))
A = [0] + A + [0]
cost = [abs(A[i+1] - A[i]) for i in range(N+1)]
cost_sum = sum(cost)
for i in range(N):
ans = cost_sum - cost[i] - cost[i+1]
ans += abs(A[i]-A[i+2])
print(ans)
``` | output | 1 | 72,356 | 1 | 144,713 |
Provide a correct Python 3 solution for this coding contest problem.
There are N sightseeing spots on the x-axis, numbered 1, 2, ..., N. Spot i is at the point with coordinate A_i. It costs |a - b| yen (the currency of Japan) to travel from a point with coordinate a to another point with coordinate b along the axis.
You planned a trip along the axis. In this plan, you first depart from the point with coordinate 0, then visit the N spots in the order they are numbered, and finally return to the point with coordinate 0.
However, something came up just before the trip, and you no longer have enough time to visit all the N spots, so you decided to choose some i and cancel the visit to Spot i. You will visit the remaining spots as planned in the order they are numbered. You will also depart from and return to the point with coordinate 0 at the beginning and the end, as planned.
For each i = 1, 2, ..., N, find the total cost of travel during the trip when the visit to Spot i is canceled.
Constraints
* 2 \leq N \leq 10^5
* -5000 \leq A_i \leq 5000 (1 \leq i \leq N)
* All input values are integers.
Input
Input is given from Standard Input in the following format:
N
A_1 A_2 ... A_N
Output
Print N lines. In the i-th line, print the total cost of travel during the trip when the visit to Spot i is canceled.
Examples
Input
3
3 5 -1
Output
12
8
10
Input
5
1 1 1 2 0
Output
4
4
4
2
4
Input
6
-679 -2409 -3258 3095 -3291 -4462
Output
21630
21630
19932
8924
21630
19288 | instruction | 0 | 72,357 | 1 | 144,714 |
"Correct Solution:
```
n = int(input())
a = [0] + list(map(int, input().split())) + [0]
move = [abs(a[i - 1] - a[i]) for i in range(1, n + 2)]
msum = sum(move)
for i in range(1, n + 1):
tmp = - move[i - 1] - move[i] + abs(a[i - 1] - a[i + 1])
print(msum + tmp)
``` | output | 1 | 72,357 | 1 | 144,715 |
Provide a correct Python 3 solution for this coding contest problem.
There are N sightseeing spots on the x-axis, numbered 1, 2, ..., N. Spot i is at the point with coordinate A_i. It costs |a - b| yen (the currency of Japan) to travel from a point with coordinate a to another point with coordinate b along the axis.
You planned a trip along the axis. In this plan, you first depart from the point with coordinate 0, then visit the N spots in the order they are numbered, and finally return to the point with coordinate 0.
However, something came up just before the trip, and you no longer have enough time to visit all the N spots, so you decided to choose some i and cancel the visit to Spot i. You will visit the remaining spots as planned in the order they are numbered. You will also depart from and return to the point with coordinate 0 at the beginning and the end, as planned.
For each i = 1, 2, ..., N, find the total cost of travel during the trip when the visit to Spot i is canceled.
Constraints
* 2 \leq N \leq 10^5
* -5000 \leq A_i \leq 5000 (1 \leq i \leq N)
* All input values are integers.
Input
Input is given from Standard Input in the following format:
N
A_1 A_2 ... A_N
Output
Print N lines. In the i-th line, print the total cost of travel during the trip when the visit to Spot i is canceled.
Examples
Input
3
3 5 -1
Output
12
8
10
Input
5
1 1 1 2 0
Output
4
4
4
2
4
Input
6
-679 -2409 -3258 3095 -3291 -4462
Output
21630
21630
19932
8924
21630
19288 | instruction | 0 | 72,358 | 1 | 144,716 |
"Correct Solution:
```
N = int(input())
A = list(map(int, input().split()))
A = [0] + A + [0]
D = [abs(A[i + 1] - A[i]) for i in range(len(A) - 1)]
total = sum(D)
for i in range(1, N + 1):
res = total + abs(A[i + 1] - A[i - 1])
res -= abs(A[i + 1] - A[i]) + abs(A[i] - A[i - 1])
print(res)
``` | output | 1 | 72,358 | 1 | 144,717 |
Provide a correct Python 3 solution for this coding contest problem.
There are N sightseeing spots on the x-axis, numbered 1, 2, ..., N. Spot i is at the point with coordinate A_i. It costs |a - b| yen (the currency of Japan) to travel from a point with coordinate a to another point with coordinate b along the axis.
You planned a trip along the axis. In this plan, you first depart from the point with coordinate 0, then visit the N spots in the order they are numbered, and finally return to the point with coordinate 0.
However, something came up just before the trip, and you no longer have enough time to visit all the N spots, so you decided to choose some i and cancel the visit to Spot i. You will visit the remaining spots as planned in the order they are numbered. You will also depart from and return to the point with coordinate 0 at the beginning and the end, as planned.
For each i = 1, 2, ..., N, find the total cost of travel during the trip when the visit to Spot i is canceled.
Constraints
* 2 \leq N \leq 10^5
* -5000 \leq A_i \leq 5000 (1 \leq i \leq N)
* All input values are integers.
Input
Input is given from Standard Input in the following format:
N
A_1 A_2 ... A_N
Output
Print N lines. In the i-th line, print the total cost of travel during the trip when the visit to Spot i is canceled.
Examples
Input
3
3 5 -1
Output
12
8
10
Input
5
1 1 1 2 0
Output
4
4
4
2
4
Input
6
-679 -2409 -3258 3095 -3291 -4462
Output
21630
21630
19932
8924
21630
19288 | instruction | 0 | 72,359 | 1 | 144,718 |
"Correct Solution:
```
n = int(input())
a = list(map(int, input().split()))
aa = [0] + a + [0]
d = [0]*(n+1)
for i in range(n+1):
d[i] = abs(aa[i]-aa[i+1])
s = sum(d)
for i in range(n):
print(s - d[i] - d[i+1] + abs(aa[i+2]-aa[i]))
``` | output | 1 | 72,359 | 1 | 144,719 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
There are N sightseeing spots on the x-axis, numbered 1, 2, ..., N. Spot i is at the point with coordinate A_i. It costs |a - b| yen (the currency of Japan) to travel from a point with coordinate a to another point with coordinate b along the axis.
You planned a trip along the axis. In this plan, you first depart from the point with coordinate 0, then visit the N spots in the order they are numbered, and finally return to the point with coordinate 0.
However, something came up just before the trip, and you no longer have enough time to visit all the N spots, so you decided to choose some i and cancel the visit to Spot i. You will visit the remaining spots as planned in the order they are numbered. You will also depart from and return to the point with coordinate 0 at the beginning and the end, as planned.
For each i = 1, 2, ..., N, find the total cost of travel during the trip when the visit to Spot i is canceled.
Constraints
* 2 \leq N \leq 10^5
* -5000 \leq A_i \leq 5000 (1 \leq i \leq N)
* All input values are integers.
Input
Input is given from Standard Input in the following format:
N
A_1 A_2 ... A_N
Output
Print N lines. In the i-th line, print the total cost of travel during the trip when the visit to Spot i is canceled.
Examples
Input
3
3 5 -1
Output
12
8
10
Input
5
1 1 1 2 0
Output
4
4
4
2
4
Input
6
-679 -2409 -3258 3095 -3291 -4462
Output
21630
21630
19932
8924
21630
19288
Submitted Solution:
```
N = int(input())
A = list(map(int,input().split()))
ls = [0] + A + [0]
ls2 = [0] * (N+1)
for n in range(N+1):
ls2[n] = abs(ls[n+1]-ls[n])
sum_ls2 = sum(ls2)
for n in range(N):
print(sum_ls2 - ls2[n] - ls2[n+1] + abs(ls[n+2]-ls[n]))
``` | instruction | 0 | 72,360 | 1 | 144,720 |
Yes | output | 1 | 72,360 | 1 | 144,721 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
There are N sightseeing spots on the x-axis, numbered 1, 2, ..., N. Spot i is at the point with coordinate A_i. It costs |a - b| yen (the currency of Japan) to travel from a point with coordinate a to another point with coordinate b along the axis.
You planned a trip along the axis. In this plan, you first depart from the point with coordinate 0, then visit the N spots in the order they are numbered, and finally return to the point with coordinate 0.
However, something came up just before the trip, and you no longer have enough time to visit all the N spots, so you decided to choose some i and cancel the visit to Spot i. You will visit the remaining spots as planned in the order they are numbered. You will also depart from and return to the point with coordinate 0 at the beginning and the end, as planned.
For each i = 1, 2, ..., N, find the total cost of travel during the trip when the visit to Spot i is canceled.
Constraints
* 2 \leq N \leq 10^5
* -5000 \leq A_i \leq 5000 (1 \leq i \leq N)
* All input values are integers.
Input
Input is given from Standard Input in the following format:
N
A_1 A_2 ... A_N
Output
Print N lines. In the i-th line, print the total cost of travel during the trip when the visit to Spot i is canceled.
Examples
Input
3
3 5 -1
Output
12
8
10
Input
5
1 1 1 2 0
Output
4
4
4
2
4
Input
6
-679 -2409 -3258 3095 -3291 -4462
Output
21630
21630
19932
8924
21630
19288
Submitted Solution:
```
n = int(input())
al = [0] + list(map(int, input().split())) + [0]
bl = [0]*(n+1)
for i in range(n+1):
bl[i] = abs(al[i] - al[i+1])
cost = sum(bl)
for i in range(n):
print(cost - sum(bl[i:i+2]) + abs(al[i] - al[i+2]))
``` | instruction | 0 | 72,361 | 1 | 144,722 |
Yes | output | 1 | 72,361 | 1 | 144,723 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
There are N sightseeing spots on the x-axis, numbered 1, 2, ..., N. Spot i is at the point with coordinate A_i. It costs |a - b| yen (the currency of Japan) to travel from a point with coordinate a to another point with coordinate b along the axis.
You planned a trip along the axis. In this plan, you first depart from the point with coordinate 0, then visit the N spots in the order they are numbered, and finally return to the point with coordinate 0.
However, something came up just before the trip, and you no longer have enough time to visit all the N spots, so you decided to choose some i and cancel the visit to Spot i. You will visit the remaining spots as planned in the order they are numbered. You will also depart from and return to the point with coordinate 0 at the beginning and the end, as planned.
For each i = 1, 2, ..., N, find the total cost of travel during the trip when the visit to Spot i is canceled.
Constraints
* 2 \leq N \leq 10^5
* -5000 \leq A_i \leq 5000 (1 \leq i \leq N)
* All input values are integers.
Input
Input is given from Standard Input in the following format:
N
A_1 A_2 ... A_N
Output
Print N lines. In the i-th line, print the total cost of travel during the trip when the visit to Spot i is canceled.
Examples
Input
3
3 5 -1
Output
12
8
10
Input
5
1 1 1 2 0
Output
4
4
4
2
4
Input
6
-679 -2409 -3258 3095 -3291 -4462
Output
21630
21630
19932
8924
21630
19288
Submitted Solution:
```
n = int(input())
A = list(map(int, input().split()))
A = [0] + A + [0]
s = 0
for i in range(1, n+2):
s += abs(A[i-1]-A[i])
for i in range(1, n+1):
s_ = s - abs(A[i-1]-A[i])-abs(A[i]-A[i+1])+abs(A[i-1]-A[i+1])
print(s_)
``` | instruction | 0 | 72,362 | 1 | 144,724 |
Yes | output | 1 | 72,362 | 1 | 144,725 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
There are N sightseeing spots on the x-axis, numbered 1, 2, ..., N. Spot i is at the point with coordinate A_i. It costs |a - b| yen (the currency of Japan) to travel from a point with coordinate a to another point with coordinate b along the axis.
You planned a trip along the axis. In this plan, you first depart from the point with coordinate 0, then visit the N spots in the order they are numbered, and finally return to the point with coordinate 0.
However, something came up just before the trip, and you no longer have enough time to visit all the N spots, so you decided to choose some i and cancel the visit to Spot i. You will visit the remaining spots as planned in the order they are numbered. You will also depart from and return to the point with coordinate 0 at the beginning and the end, as planned.
For each i = 1, 2, ..., N, find the total cost of travel during the trip when the visit to Spot i is canceled.
Constraints
* 2 \leq N \leq 10^5
* -5000 \leq A_i \leq 5000 (1 \leq i \leq N)
* All input values are integers.
Input
Input is given from Standard Input in the following format:
N
A_1 A_2 ... A_N
Output
Print N lines. In the i-th line, print the total cost of travel during the trip when the visit to Spot i is canceled.
Examples
Input
3
3 5 -1
Output
12
8
10
Input
5
1 1 1 2 0
Output
4
4
4
2
4
Input
6
-679 -2409 -3258 3095 -3291 -4462
Output
21630
21630
19932
8924
21630
19288
Submitted Solution:
```
n = int(input())
a = [0] + list(map(int, input().split())) + [0]
total = 0
for i in range(n+1):
total += abs(a[i] - a[i + 1])
for i in range(1,n+1):
print(total + abs(a[i-1] - a[i + 1]) - abs(a[i - 1] - a[i]) - abs(a[i] - a[i + 1]))
``` | instruction | 0 | 72,363 | 1 | 144,726 |
Yes | output | 1 | 72,363 | 1 | 144,727 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
There are N sightseeing spots on the x-axis, numbered 1, 2, ..., N. Spot i is at the point with coordinate A_i. It costs |a - b| yen (the currency of Japan) to travel from a point with coordinate a to another point with coordinate b along the axis.
You planned a trip along the axis. In this plan, you first depart from the point with coordinate 0, then visit the N spots in the order they are numbered, and finally return to the point with coordinate 0.
However, something came up just before the trip, and you no longer have enough time to visit all the N spots, so you decided to choose some i and cancel the visit to Spot i. You will visit the remaining spots as planned in the order they are numbered. You will also depart from and return to the point with coordinate 0 at the beginning and the end, as planned.
For each i = 1, 2, ..., N, find the total cost of travel during the trip when the visit to Spot i is canceled.
Constraints
* 2 \leq N \leq 10^5
* -5000 \leq A_i \leq 5000 (1 \leq i \leq N)
* All input values are integers.
Input
Input is given from Standard Input in the following format:
N
A_1 A_2 ... A_N
Output
Print N lines. In the i-th line, print the total cost of travel during the trip when the visit to Spot i is canceled.
Examples
Input
3
3 5 -1
Output
12
8
10
Input
5
1 1 1 2 0
Output
4
4
4
2
4
Input
6
-679 -2409 -3258 3095 -3291 -4462
Output
21630
21630
19932
8924
21630
19288
Submitted Solution:
```
import numpy as np
N = int(input())
A = list(map(int, input().split()))
A.insert(0, 0)
A.append(0)
mx = np.sum(np.abs(np.diff(A)))
for i in range(1, N+1):
if A[i] >= 0 and A[i] <= A[i+1]:
print(mx)
elif A[i] < 0 and A[i] >= A[i+1]:
print(mx)
else:
if i == N and A[i] * A[i-1] < 0:
print(mx - np.abs(A[i]-A[i+1])*2)
else:
print(mx - np.abs(A[i]-A[i-1])*2)
``` | instruction | 0 | 72,364 | 1 | 144,728 |
No | output | 1 | 72,364 | 1 | 144,729 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
There are N sightseeing spots on the x-axis, numbered 1, 2, ..., N. Spot i is at the point with coordinate A_i. It costs |a - b| yen (the currency of Japan) to travel from a point with coordinate a to another point with coordinate b along the axis.
You planned a trip along the axis. In this plan, you first depart from the point with coordinate 0, then visit the N spots in the order they are numbered, and finally return to the point with coordinate 0.
However, something came up just before the trip, and you no longer have enough time to visit all the N spots, so you decided to choose some i and cancel the visit to Spot i. You will visit the remaining spots as planned in the order they are numbered. You will also depart from and return to the point with coordinate 0 at the beginning and the end, as planned.
For each i = 1, 2, ..., N, find the total cost of travel during the trip when the visit to Spot i is canceled.
Constraints
* 2 \leq N \leq 10^5
* -5000 \leq A_i \leq 5000 (1 \leq i \leq N)
* All input values are integers.
Input
Input is given from Standard Input in the following format:
N
A_1 A_2 ... A_N
Output
Print N lines. In the i-th line, print the total cost of travel during the trip when the visit to Spot i is canceled.
Examples
Input
3
3 5 -1
Output
12
8
10
Input
5
1 1 1 2 0
Output
4
4
4
2
4
Input
6
-679 -2409 -3258 3095 -3291 -4462
Output
21630
21630
19932
8924
21630
19288
Submitted Solution:
```
N = int(input())
A = list(map(int, input().split()))
A = [0] + A + [0]
cost = [abs(A[i+1] - A[i]) for i in range(N+1)]
for i in range(N):
ans = sum(cost) - cost[i] - cost[i+1]
ans += abs(A[i]-A[i+2])
print(ans)
``` | instruction | 0 | 72,365 | 1 | 144,730 |
No | output | 1 | 72,365 | 1 | 144,731 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
There are N sightseeing spots on the x-axis, numbered 1, 2, ..., N. Spot i is at the point with coordinate A_i. It costs |a - b| yen (the currency of Japan) to travel from a point with coordinate a to another point with coordinate b along the axis.
You planned a trip along the axis. In this plan, you first depart from the point with coordinate 0, then visit the N spots in the order they are numbered, and finally return to the point with coordinate 0.
However, something came up just before the trip, and you no longer have enough time to visit all the N spots, so you decided to choose some i and cancel the visit to Spot i. You will visit the remaining spots as planned in the order they are numbered. You will also depart from and return to the point with coordinate 0 at the beginning and the end, as planned.
For each i = 1, 2, ..., N, find the total cost of travel during the trip when the visit to Spot i is canceled.
Constraints
* 2 \leq N \leq 10^5
* -5000 \leq A_i \leq 5000 (1 \leq i \leq N)
* All input values are integers.
Input
Input is given from Standard Input in the following format:
N
A_1 A_2 ... A_N
Output
Print N lines. In the i-th line, print the total cost of travel during the trip when the visit to Spot i is canceled.
Examples
Input
3
3 5 -1
Output
12
8
10
Input
5
1 1 1 2 0
Output
4
4
4
2
4
Input
6
-679 -2409 -3258 3095 -3291 -4462
Output
21630
21630
19932
8924
21630
19288
Submitted Solution:
```
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import sys
N = int(sys.stdin.readline())
A = sys.stdin.readline().split(' ')
for rem in range(len(A)):
pay = 0
B = A[:]
del(B[rem])
for i in range(len(B)):
a = int(B[i])
s = int(B[i - 1]) if i > 0 else 0
l = a - s
pay += l if l > 0 else -l
lastPoint = int(B[len(B) - 1])
pay += lastPoint if lastPoint > 0 else -lastPoint
print(pay)
``` | instruction | 0 | 72,366 | 1 | 144,732 |
No | output | 1 | 72,366 | 1 | 144,733 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
There are N sightseeing spots on the x-axis, numbered 1, 2, ..., N. Spot i is at the point with coordinate A_i. It costs |a - b| yen (the currency of Japan) to travel from a point with coordinate a to another point with coordinate b along the axis.
You planned a trip along the axis. In this plan, you first depart from the point with coordinate 0, then visit the N spots in the order they are numbered, and finally return to the point with coordinate 0.
However, something came up just before the trip, and you no longer have enough time to visit all the N spots, so you decided to choose some i and cancel the visit to Spot i. You will visit the remaining spots as planned in the order they are numbered. You will also depart from and return to the point with coordinate 0 at the beginning and the end, as planned.
For each i = 1, 2, ..., N, find the total cost of travel during the trip when the visit to Spot i is canceled.
Constraints
* 2 \leq N \leq 10^5
* -5000 \leq A_i \leq 5000 (1 \leq i \leq N)
* All input values are integers.
Input
Input is given from Standard Input in the following format:
N
A_1 A_2 ... A_N
Output
Print N lines. In the i-th line, print the total cost of travel during the trip when the visit to Spot i is canceled.
Examples
Input
3
3 5 -1
Output
12
8
10
Input
5
1 1 1 2 0
Output
4
4
4
2
4
Input
6
-679 -2409 -3258 3095 -3291 -4462
Output
21630
21630
19932
8924
21630
19288
Submitted Solution:
```
N = int(input())
A = [0]+list(map(int,input().split()))+[0]
B = []
for i in range(N+1):
B.append(abs(A[i]-A[i+1]))
for i in range(N):
print(sum(B)-B[i]-B[i+1]+abs(A[i]-A[i+2]))
``` | instruction | 0 | 72,367 | 1 | 144,734 |
No | output | 1 | 72,367 | 1 | 144,735 |
Provide a correct Python 3 solution for this coding contest problem.
In the year 2168, AtCoder Inc., which is much larger than now, is starting a limited express train service called AtCoder Express.
In the plan developed by the president Takahashi, the trains will run as follows:
* A train will run for (t_1 + t_2 + t_3 + ... + t_N) seconds.
* In the first t_1 seconds, a train must run at a speed of at most v_1 m/s (meters per second). Similarly, in the subsequent t_2 seconds, a train must run at a speed of at most v_2 m/s, and so on.
According to the specifications of the trains, the acceleration of a train must be always within ±1m/s^2. Additionally, a train must stop at the beginning and the end of the run.
Find the maximum possible distance that a train can cover in the run.
Constraints
* 1 \leq N \leq 100
* 1 \leq t_i \leq 200
* 1 \leq v_i \leq 100
* All input values are integers.
Input
Input is given from Standard Input in the following format:
N
t_1 t_2 t_3 … t_N
v_1 v_2 v_3 … v_N
Output
Print the maximum possible that a train can cover in the run.
Output is considered correct if its absolute difference from the judge's output is at most 10^{-3}.
Examples
Input
1
100
30
Output
2100.000000000000000
Input
2
60 50
34 38
Output
2632.000000000000000
Input
3
12 14 2
6 2 7
Output
76.000000000000000
Input
1
9
10
Output
20.250000000000000000
Input
10
64 55 27 35 76 119 7 18 49 100
29 19 31 39 27 48 41 87 55 70
Output
20291.000000000000 | instruction | 0 | 72,368 | 1 | 144,736 |
"Correct Solution:
```
n = int(input())
t = list(map(int, input().split()))
v = list(map(int, input().split()))
runtime = sum(t)
speed = [0] * (runtime*2+1)
now_t, now_v = 0,0
for ti,vi in zip(t,v):
for i in range(now_t*2+1,now_t*2+ti*2+1):
next_v = min(now_v+0.5, vi)
speed[i] = next_v
now_v = next_v
now_t += ti
speed[-1] = 0
now_t, now_v = runtime,0
for ti,vi in zip(t[::-1],v[::-1]):
for i in range(now_t*2-1,now_t*2-ti*2-1,-1):
next_v = min([now_v+0.5, speed[i],vi])
speed[i] = next_v
now_v = next_v
now_t -= ti
ans = 0
for i in range(runtime*2):
ans += speed[i]+speed[i+1]
ans /= 4
print(ans)
``` | output | 1 | 72,368 | 1 | 144,737 |
Provide a correct Python 3 solution for this coding contest problem.
In the year 2168, AtCoder Inc., which is much larger than now, is starting a limited express train service called AtCoder Express.
In the plan developed by the president Takahashi, the trains will run as follows:
* A train will run for (t_1 + t_2 + t_3 + ... + t_N) seconds.
* In the first t_1 seconds, a train must run at a speed of at most v_1 m/s (meters per second). Similarly, in the subsequent t_2 seconds, a train must run at a speed of at most v_2 m/s, and so on.
According to the specifications of the trains, the acceleration of a train must be always within ±1m/s^2. Additionally, a train must stop at the beginning and the end of the run.
Find the maximum possible distance that a train can cover in the run.
Constraints
* 1 \leq N \leq 100
* 1 \leq t_i \leq 200
* 1 \leq v_i \leq 100
* All input values are integers.
Input
Input is given from Standard Input in the following format:
N
t_1 t_2 t_3 … t_N
v_1 v_2 v_3 … v_N
Output
Print the maximum possible that a train can cover in the run.
Output is considered correct if its absolute difference from the judge's output is at most 10^{-3}.
Examples
Input
1
100
30
Output
2100.000000000000000
Input
2
60 50
34 38
Output
2632.000000000000000
Input
3
12 14 2
6 2 7
Output
76.000000000000000
Input
1
9
10
Output
20.250000000000000000
Input
10
64 55 27 35 76 119 7 18 49 100
29 19 31 39 27 48 41 87 55 70
Output
20291.000000000000 | instruction | 0 | 72,369 | 1 | 144,738 |
"Correct Solution:
```
N = int(input())
T = [int(i) for i in input().split()]
V = [int(i) for i in input().split()]
T_p = [0,0]
temp = 0
for tt in T:
temp += tt
T_p.append(temp)
T_p.append(temp)
Tmax = temp
def vv(i,tt):
a = T_p[i]
b = T_p[i + 1]
if i == 0 or i == N + 1:
vmax = 0
else:
vmax = V[i - 1]
if tt >= b:
res = tt - b + vmax
elif tt <= a:
res = a - tt + vmax
else:
res = vmax
return res
mints = [min([vv(i, tt/2) for i in range(N + 2)]) for tt in range(2 * Tmax + 1)]
res = 0
for i in range(len(mints) -1 ):
res += (mints[i] + mints[i + 1])/4
print(res)
``` | output | 1 | 72,369 | 1 | 144,739 |
Provide a correct Python 3 solution for this coding contest problem.
In the year 2168, AtCoder Inc., which is much larger than now, is starting a limited express train service called AtCoder Express.
In the plan developed by the president Takahashi, the trains will run as follows:
* A train will run for (t_1 + t_2 + t_3 + ... + t_N) seconds.
* In the first t_1 seconds, a train must run at a speed of at most v_1 m/s (meters per second). Similarly, in the subsequent t_2 seconds, a train must run at a speed of at most v_2 m/s, and so on.
According to the specifications of the trains, the acceleration of a train must be always within ±1m/s^2. Additionally, a train must stop at the beginning and the end of the run.
Find the maximum possible distance that a train can cover in the run.
Constraints
* 1 \leq N \leq 100
* 1 \leq t_i \leq 200
* 1 \leq v_i \leq 100
* All input values are integers.
Input
Input is given from Standard Input in the following format:
N
t_1 t_2 t_3 … t_N
v_1 v_2 v_3 … v_N
Output
Print the maximum possible that a train can cover in the run.
Output is considered correct if its absolute difference from the judge's output is at most 10^{-3}.
Examples
Input
1
100
30
Output
2100.000000000000000
Input
2
60 50
34 38
Output
2632.000000000000000
Input
3
12 14 2
6 2 7
Output
76.000000000000000
Input
1
9
10
Output
20.250000000000000000
Input
10
64 55 27 35 76 119 7 18 49 100
29 19 31 39 27 48 41 87 55 70
Output
20291.000000000000 | instruction | 0 | 72,370 | 1 | 144,740 |
"Correct Solution:
```
N = int(input())
tli = [ int(it)*2 for it in input().split() ]
vli = [ int(it)*2 for it in input().split() ]
vmax = [0]
for i in range(len(tli)):
tmp = vmax.pop()
vmax.append( min(tmp,vli[i]) )
vmax.extend( [vli[i]]*(tli[i]) )
vmax[-1]=(0)
vmax[0]=0
T = len( vmax ) - 1
for j in range( 1000 ):
for i in range( T ):
vmax[i+1] = min( vmax[i]+1 , vmax[i+1] )
for i in range( T,0,-1):
vmax[i-1] = min( vmax[i]+1 , vmax[i-1] )
if (j==0):
pass
#print ( vmax )
print ( 0.25 * sum(vmax) )
``` | output | 1 | 72,370 | 1 | 144,741 |
Provide a correct Python 3 solution for this coding contest problem.
In the year 2168, AtCoder Inc., which is much larger than now, is starting a limited express train service called AtCoder Express.
In the plan developed by the president Takahashi, the trains will run as follows:
* A train will run for (t_1 + t_2 + t_3 + ... + t_N) seconds.
* In the first t_1 seconds, a train must run at a speed of at most v_1 m/s (meters per second). Similarly, in the subsequent t_2 seconds, a train must run at a speed of at most v_2 m/s, and so on.
According to the specifications of the trains, the acceleration of a train must be always within ±1m/s^2. Additionally, a train must stop at the beginning and the end of the run.
Find the maximum possible distance that a train can cover in the run.
Constraints
* 1 \leq N \leq 100
* 1 \leq t_i \leq 200
* 1 \leq v_i \leq 100
* All input values are integers.
Input
Input is given from Standard Input in the following format:
N
t_1 t_2 t_3 … t_N
v_1 v_2 v_3 … v_N
Output
Print the maximum possible that a train can cover in the run.
Output is considered correct if its absolute difference from the judge's output is at most 10^{-3}.
Examples
Input
1
100
30
Output
2100.000000000000000
Input
2
60 50
34 38
Output
2632.000000000000000
Input
3
12 14 2
6 2 7
Output
76.000000000000000
Input
1
9
10
Output
20.250000000000000000
Input
10
64 55 27 35 76 119 7 18 49 100
29 19 31 39 27 48 41 87 55 70
Output
20291.000000000000 | instruction | 0 | 72,371 | 1 | 144,742 |
"Correct Solution:
```
import sys
sys.setrecursionlimit(10000000)
MOD = 10 ** 9 + 7
INF = 10 ** 15
N = int(input())
T = list(map(int,input().split()))
V = list(map(int,input().split()))
def calc_area(v1,v2,t,lim):
if v1 > v2:
v1,v2 = v2,v1
if v2 == lim:
if lim - v1 < t:
return t*lim - (lim - v1)*(lim - v1)/2
else:
return (v1 + v2)*t/2
else:
if 2*lim - v1 - v2 < t:
return t*lim - (lim - v1)*(lim - v1)/2 - (lim - v2)*(lim - v2)/2
else:
mid = (t + v2 - v1)/2
return (mid + 2*v1)*mid/2 + (t - mid + 2*v2)*(t - mid)/2
def calc(N,T,V,maxv):
ans = 0
v = 0
for i in range(N):
next_v = min(v + T[i],maxv[i])
ans += calc_area(v,next_v,T[i],V[i])
v = next_v
return ans
maxV = [0] * N
for i in range(N - 2,-1,-1):
maxV[i] = min(maxV[i + 1] + T[i + 1],V[i],V[i + 1])
ans = calc(N,T,V,maxV)
print(ans)
``` | output | 1 | 72,371 | 1 | 144,743 |
Provide a correct Python 3 solution for this coding contest problem.
In the year 2168, AtCoder Inc., which is much larger than now, is starting a limited express train service called AtCoder Express.
In the plan developed by the president Takahashi, the trains will run as follows:
* A train will run for (t_1 + t_2 + t_3 + ... + t_N) seconds.
* In the first t_1 seconds, a train must run at a speed of at most v_1 m/s (meters per second). Similarly, in the subsequent t_2 seconds, a train must run at a speed of at most v_2 m/s, and so on.
According to the specifications of the trains, the acceleration of a train must be always within ±1m/s^2. Additionally, a train must stop at the beginning and the end of the run.
Find the maximum possible distance that a train can cover in the run.
Constraints
* 1 \leq N \leq 100
* 1 \leq t_i \leq 200
* 1 \leq v_i \leq 100
* All input values are integers.
Input
Input is given from Standard Input in the following format:
N
t_1 t_2 t_3 … t_N
v_1 v_2 v_3 … v_N
Output
Print the maximum possible that a train can cover in the run.
Output is considered correct if its absolute difference from the judge's output is at most 10^{-3}.
Examples
Input
1
100
30
Output
2100.000000000000000
Input
2
60 50
34 38
Output
2632.000000000000000
Input
3
12 14 2
6 2 7
Output
76.000000000000000
Input
1
9
10
Output
20.250000000000000000
Input
10
64 55 27 35 76 119 7 18 49 100
29 19 31 39 27 48 41 87 55 70
Output
20291.000000000000 | instruction | 0 | 72,372 | 1 | 144,744 |
"Correct Solution:
```
'''
38分あたり
https://www.youtube.com/watch?v=T1zXzsoK268
'''
def input_num_list(): return list(map(int, input().split()))
n = int(input())
t = input_num_list()
T = sum(t)
v = input_num_list()
maxv = [100 for _ in range(2 * T + 1)]
maxv[0] = 0
maxv[2 * T] = 0
t_l, t_r = 0, 0
for i in range(n):
t_l = t_r
t_r += t[i]
vv = v[i]
for j in range(2 * t_l, 2 * t_r + 1):
maxv[j] = min(maxv[j], vv)
#print(maxv)
i = 1
while i <= 2 * T:
maxv[i] = min(maxv[i], maxv[i - 1] + 0.5)
i += 1
#print(maxv)
i = 2 * T - 1
while i >= 0:
maxv[i] = min(maxv[i], maxv[i + 1] + 0.5)
i -= 1
#print(maxv)
ans = 0
i = 0
while i <= 2 * T - 1:
ans += 0.25 * (maxv[i] + maxv[i + 1])
i += 1
print(ans)
#print(maxv)
``` | output | 1 | 72,372 | 1 | 144,745 |
Provide a correct Python 3 solution for this coding contest problem.
In the year 2168, AtCoder Inc., which is much larger than now, is starting a limited express train service called AtCoder Express.
In the plan developed by the president Takahashi, the trains will run as follows:
* A train will run for (t_1 + t_2 + t_3 + ... + t_N) seconds.
* In the first t_1 seconds, a train must run at a speed of at most v_1 m/s (meters per second). Similarly, in the subsequent t_2 seconds, a train must run at a speed of at most v_2 m/s, and so on.
According to the specifications of the trains, the acceleration of a train must be always within ±1m/s^2. Additionally, a train must stop at the beginning and the end of the run.
Find the maximum possible distance that a train can cover in the run.
Constraints
* 1 \leq N \leq 100
* 1 \leq t_i \leq 200
* 1 \leq v_i \leq 100
* All input values are integers.
Input
Input is given from Standard Input in the following format:
N
t_1 t_2 t_3 … t_N
v_1 v_2 v_3 … v_N
Output
Print the maximum possible that a train can cover in the run.
Output is considered correct if its absolute difference from the judge's output is at most 10^{-3}.
Examples
Input
1
100
30
Output
2100.000000000000000
Input
2
60 50
34 38
Output
2632.000000000000000
Input
3
12 14 2
6 2 7
Output
76.000000000000000
Input
1
9
10
Output
20.250000000000000000
Input
10
64 55 27 35 76 119 7 18 49 100
29 19 31 39 27 48 41 87 55 70
Output
20291.000000000000 | instruction | 0 | 72,373 | 1 | 144,746 |
"Correct Solution:
```
# -*- coding: utf-8 -*-
from itertools import accumulate
N = int(input())
T = list(map(int, input().split()))
V = list(map(int, input().split()))
clock = [0] + list(accumulate(T))
t_sum = sum(T)
mn_f = 0
ans = 0
for t in range(2 * t_sum):
t /= 2
mn = min(t, t_sum - t)
for i in range(1, len(clock)):
v = V[i-1]
if t < clock[i-1]:
v_max = v + clock[i-1] - t
elif clock[i-1] <= t <= clock[i]:
v_max = v
else:
v_max = v + t - clock[i]
mn = min(mn, v_max)
ans += (mn_f + mn) * 0.25
mn_f = mn
ans += mn_f * 0.25
print(ans)
``` | output | 1 | 72,373 | 1 | 144,747 |
Provide a correct Python 3 solution for this coding contest problem.
In the year 2168, AtCoder Inc., which is much larger than now, is starting a limited express train service called AtCoder Express.
In the plan developed by the president Takahashi, the trains will run as follows:
* A train will run for (t_1 + t_2 + t_3 + ... + t_N) seconds.
* In the first t_1 seconds, a train must run at a speed of at most v_1 m/s (meters per second). Similarly, in the subsequent t_2 seconds, a train must run at a speed of at most v_2 m/s, and so on.
According to the specifications of the trains, the acceleration of a train must be always within ±1m/s^2. Additionally, a train must stop at the beginning and the end of the run.
Find the maximum possible distance that a train can cover in the run.
Constraints
* 1 \leq N \leq 100
* 1 \leq t_i \leq 200
* 1 \leq v_i \leq 100
* All input values are integers.
Input
Input is given from Standard Input in the following format:
N
t_1 t_2 t_3 … t_N
v_1 v_2 v_3 … v_N
Output
Print the maximum possible that a train can cover in the run.
Output is considered correct if its absolute difference from the judge's output is at most 10^{-3}.
Examples
Input
1
100
30
Output
2100.000000000000000
Input
2
60 50
34 38
Output
2632.000000000000000
Input
3
12 14 2
6 2 7
Output
76.000000000000000
Input
1
9
10
Output
20.250000000000000000
Input
10
64 55 27 35 76 119 7 18 49 100
29 19 31 39 27 48 41 87 55 70
Output
20291.000000000000 | instruction | 0 | 72,374 | 1 | 144,748 |
"Correct Solution:
```
N = int(input())
T = list(map(lambda t: int(t) * 10, input().split()))
V = list(map(int, input().split())) + [0]
R = sum(T)
maxSpeed = [10**18] * (R + 1)
maxSpeed[0] = 0
maxSpeed[R] = 0
now = 0
for i, t in enumerate(T):
now += t
maxSpeed[now] = min(V[i], V[i + 1])
now = 0
for v, t in zip(V, T):
for i in range(t + 1):
maxSpeed[now + i] = min(maxSpeed[now + i], v)
now += t
for t in range(1, R + 1):
maxSpeed[t] = min(maxSpeed[t], maxSpeed[t - 1] + 0.1)
for t in range(R)[::-1]:
maxSpeed[t] = min(maxSpeed[t], maxSpeed[t + 1] + 0.1)
base = 0
upper = 0
for v1, v2 in zip(maxSpeed, maxSpeed[1:]):
base += min(v1, v2)
upper += abs(v1 - v2)
ans = base + upper / 2
print(ans / 10)
``` | output | 1 | 72,374 | 1 | 144,749 |
Provide a correct Python 3 solution for this coding contest problem.
In the year 2168, AtCoder Inc., which is much larger than now, is starting a limited express train service called AtCoder Express.
In the plan developed by the president Takahashi, the trains will run as follows:
* A train will run for (t_1 + t_2 + t_3 + ... + t_N) seconds.
* In the first t_1 seconds, a train must run at a speed of at most v_1 m/s (meters per second). Similarly, in the subsequent t_2 seconds, a train must run at a speed of at most v_2 m/s, and so on.
According to the specifications of the trains, the acceleration of a train must be always within ±1m/s^2. Additionally, a train must stop at the beginning and the end of the run.
Find the maximum possible distance that a train can cover in the run.
Constraints
* 1 \leq N \leq 100
* 1 \leq t_i \leq 200
* 1 \leq v_i \leq 100
* All input values are integers.
Input
Input is given from Standard Input in the following format:
N
t_1 t_2 t_3 … t_N
v_1 v_2 v_3 … v_N
Output
Print the maximum possible that a train can cover in the run.
Output is considered correct if its absolute difference from the judge's output is at most 10^{-3}.
Examples
Input
1
100
30
Output
2100.000000000000000
Input
2
60 50
34 38
Output
2632.000000000000000
Input
3
12 14 2
6 2 7
Output
76.000000000000000
Input
1
9
10
Output
20.250000000000000000
Input
10
64 55 27 35 76 119 7 18 49 100
29 19 31 39 27 48 41 87 55 70
Output
20291.000000000000 | instruction | 0 | 72,375 | 1 | 144,750 |
"Correct Solution:
```
N = int(input())
T = list(map(int, input().split()))
V = list(map(int, input().split()))
V = [0] + V + [0]
# 0.前処理
# N+2個の条件をつくる
left = [0]
right = [0]
for i in range(N):
left.append(right[i])
right.append(left[-1]+T[i])
left.append(right[-1])
right.append(right[-1])
INF = float("inf")
vel = [INF]*(2*right[-1]+1)
# 1.各ステップでの許容測度の最大値の最小値を求める
for t in range(2*right[-1]+1):
for i in range(N+2):
if (t/2) < left[i]:
vel[t] = min(vel[t], -(t/2)+(V[i]+left[i]))
elif left[i] <= (t/2) and (t/2) <= right[i]:
vel[t] = min(vel[t], V[i])
elif (t/2) > right[i]:
vel[t] = min(vel[t], (t/2)+(V[i]-right[i]))
# 2.面積を求める
ans = 0
for t in range(2*right[-1]):
ans += (1/2)*0.5*(vel[t]+vel[t+1])
print(ans)
``` | output | 1 | 72,375 | 1 | 144,751 |
Provide a correct Python 3 solution for this coding contest problem.
Bridge Removal
ICPC islands once had been a popular tourist destination. For nature preservation, however, the government decided to prohibit entrance to the islands, and to remove all the man-made structures there. The hardest part of the project is to remove all the bridges connecting the islands.
There are n islands and n-1 bridges. The bridges are built so that all the islands are reachable from all the other islands by crossing one or more bridges. The bridge removal team can choose any island as the starting point, and can repeat either of the following steps.
* Move to another island by crossing a bridge that is connected to the current island.
* Remove one bridge that is connected to the current island, and stay at the same island after the removal.
Of course, a bridge, once removed, cannot be crossed in either direction. Crossing or removing a bridge both takes time proportional to the length of the bridge. Your task is to compute the shortest time necessary for removing all the bridges. Note that the island where the team starts can differ from where the team finishes the work.
Input
The input consists of at most 100 datasets. Each dataset is formatted as follows.
> n
> p2 p3 ... pn
> d2 d3 ... dn
The first integer n (3 ≤ n ≤ 800) is the number of the islands. The islands are numbered from 1 to n. The second line contains n-1 island numbers pi (1 ≤ pi < i), and tells that for each i from 2 to n the island i and the island pi are connected by a bridge. The third line contains n-1 integers di (1 ≤ di ≤ 100,000) each denoting the length of the corresponding bridge. That is, the length of the bridge connecting the island i and pi is di. It takes di units of time to cross the bridge, and also the same units of time to remove it. Note that, with this input format, it is assured that all the islands are reachable each other by crossing one or more bridges.
The input ends with a line with a single zero.
Output
For each dataset, print the minimum time units required to remove all the bridges in a single line. Each line should not have any character other than this number.
Sample Input
4
1 2 3
10 20 30
10
1 2 2 1 5 5 1 8 8
10 1 1 20 1 1 30 1 1
3
1 1
1 1
0
Output for the Sample Input
80
136
2
Example
Input
4
1 2 3
10 20 30
10
1 2 2 1 5 5 1 8 8
10 1 1 20 1 1 30 1 1
3
1 1
1 1
0
Output
80
136
2 | instruction | 0 | 72,445 | 1 | 144,890 |
"Correct Solution:
```
from sys import setrecursionlimit
setrecursionlimit(10 ** 8)
while True:
n = int(input())
if n == 0:
break
P = [int(i) for i in input().split()]
D = [int(i) for i in input().split()]
E = [list() for i in range(n + 1)]
for i, (p, c) in enumerate(zip(P, D), 2):
E[i].append((p, c))
E[p].append((i, c))
ans = 3 * sum(D)
visited = [False] * (n + 1)
is_leaf = [len(E[i]) == 1 for i in range(n + 1)]
ans -= 2 * sum(E[i][0][1] for i in range(n + 1) if is_leaf[i])
def dfs(i):
visited[i] = True
res = 0
for e, c in E[i]:
if is_leaf[e] or visited[e]:
continue
res = max(res, dfs(e) + c)
return res
r = 0
for i in range(1, n + 1):
if is_leaf[i]:
continue
visited = [False] * (n + 1)
r = max(r, dfs(i))
print(ans - r)
``` | output | 1 | 72,445 | 1 | 144,891 |
Provide a correct Python 3 solution for this coding contest problem.
Bridge Removal
ICPC islands once had been a popular tourist destination. For nature preservation, however, the government decided to prohibit entrance to the islands, and to remove all the man-made structures there. The hardest part of the project is to remove all the bridges connecting the islands.
There are n islands and n-1 bridges. The bridges are built so that all the islands are reachable from all the other islands by crossing one or more bridges. The bridge removal team can choose any island as the starting point, and can repeat either of the following steps.
* Move to another island by crossing a bridge that is connected to the current island.
* Remove one bridge that is connected to the current island, and stay at the same island after the removal.
Of course, a bridge, once removed, cannot be crossed in either direction. Crossing or removing a bridge both takes time proportional to the length of the bridge. Your task is to compute the shortest time necessary for removing all the bridges. Note that the island where the team starts can differ from where the team finishes the work.
Input
The input consists of at most 100 datasets. Each dataset is formatted as follows.
> n
> p2 p3 ... pn
> d2 d3 ... dn
The first integer n (3 ≤ n ≤ 800) is the number of the islands. The islands are numbered from 1 to n. The second line contains n-1 island numbers pi (1 ≤ pi < i), and tells that for each i from 2 to n the island i and the island pi are connected by a bridge. The third line contains n-1 integers di (1 ≤ di ≤ 100,000) each denoting the length of the corresponding bridge. That is, the length of the bridge connecting the island i and pi is di. It takes di units of time to cross the bridge, and also the same units of time to remove it. Note that, with this input format, it is assured that all the islands are reachable each other by crossing one or more bridges.
The input ends with a line with a single zero.
Output
For each dataset, print the minimum time units required to remove all the bridges in a single line. Each line should not have any character other than this number.
Sample Input
4
1 2 3
10 20 30
10
1 2 2 1 5 5 1 8 8
10 1 1 20 1 1 30 1 1
3
1 1
1 1
0
Output for the Sample Input
80
136
2
Example
Input
4
1 2 3
10 20 30
10
1 2 2 1 5 5 1 8 8
10 1 1 20 1 1 30 1 1
3
1 1
1 1
0
Output
80
136
2 | instruction | 0 | 72,446 | 1 | 144,892 |
"Correct Solution:
```
def solve():
from collections import deque
def dfs(start, turn=False):
path = deque()
path.append(start)
bridge_lengths = deque()
bridge_lengths.append(0)
unvisited = [True] * (n + 1)
unvisited[start] = False
rest = core_islands_num - 1
diameter = 0
end_point = start
while True:
u = path[-1]
for i, d in adj_list[u]:
if unvisited[i]:
path.append(i)
unvisited[i] = False
rest -= 1
bridge_lengths.append(d)
break
else:
distance = sum(bridge_lengths)
if diameter < distance:
diameter = distance
end_point = u
if rest == 0:
break
path.pop()
bridge_lengths.pop()
if turn:
return diameter
else:
return end_point
import sys
file_input = sys.stdin
while True:
n = int(file_input.readline())
if n == 0:
break
p = list(map(int, file_input.readline().split()))
d = list(map(int, file_input.readline().split()))
end_bridges_weight = 0
core_islands_num = n
adj_list = [[] for i in range(n + 1)]
s = 1
for i1, i2, b_l in zip(range(2, n + 1), p, d):
if i1 not in p[i1-1:]:
end_bridges_weight += b_l
core_islands_num -= 1
else:
s = i1
adj_list[i1].append((i2, b_l))
adj_list[i2].append((i1, b_l))
if p.count(1) == 1:
del adj_list[2][0]
end_bridges_weight += d[0]
core_islands_num -= 1
e = dfs(s)
dm = dfs(e, turn=True)
ans = sum(d) * 3 - end_bridges_weight * 2 - dm
print(ans)
solve()
``` | output | 1 | 72,446 | 1 | 144,893 |
Provide a correct Python 3 solution for this coding contest problem.
Bridge Removal
ICPC islands once had been a popular tourist destination. For nature preservation, however, the government decided to prohibit entrance to the islands, and to remove all the man-made structures there. The hardest part of the project is to remove all the bridges connecting the islands.
There are n islands and n-1 bridges. The bridges are built so that all the islands are reachable from all the other islands by crossing one or more bridges. The bridge removal team can choose any island as the starting point, and can repeat either of the following steps.
* Move to another island by crossing a bridge that is connected to the current island.
* Remove one bridge that is connected to the current island, and stay at the same island after the removal.
Of course, a bridge, once removed, cannot be crossed in either direction. Crossing or removing a bridge both takes time proportional to the length of the bridge. Your task is to compute the shortest time necessary for removing all the bridges. Note that the island where the team starts can differ from where the team finishes the work.
Input
The input consists of at most 100 datasets. Each dataset is formatted as follows.
> n
> p2 p3 ... pn
> d2 d3 ... dn
The first integer n (3 ≤ n ≤ 800) is the number of the islands. The islands are numbered from 1 to n. The second line contains n-1 island numbers pi (1 ≤ pi < i), and tells that for each i from 2 to n the island i and the island pi are connected by a bridge. The third line contains n-1 integers di (1 ≤ di ≤ 100,000) each denoting the length of the corresponding bridge. That is, the length of the bridge connecting the island i and pi is di. It takes di units of time to cross the bridge, and also the same units of time to remove it. Note that, with this input format, it is assured that all the islands are reachable each other by crossing one or more bridges.
The input ends with a line with a single zero.
Output
For each dataset, print the minimum time units required to remove all the bridges in a single line. Each line should not have any character other than this number.
Sample Input
4
1 2 3
10 20 30
10
1 2 2 1 5 5 1 8 8
10 1 1 20 1 1 30 1 1
3
1 1
1 1
0
Output for the Sample Input
80
136
2
Example
Input
4
1 2 3
10 20 30
10
1 2 2 1 5 5 1 8 8
10 1 1 20 1 1 30 1 1
3
1 1
1 1
0
Output
80
136
2 | instruction | 0 | 72,447 | 1 | 144,894 |
"Correct Solution:
```
import math,string,itertools,fractions,heapq,collections,re,array,bisect,sys,random,time,copy,functools
sys.setrecursionlimit(10**7)
inf = 10**20
eps = 1.0 / 10**13
mod = 10**9+7
dd = [(-1,0),(0,1),(1,0),(0,-1)]
ddn = [(-1,0),(-1,1),(0,1),(1,1),(1,0),(1,-1),(0,-1),(-1,-1)]
def LI(): return [int(x) for x in sys.stdin.readline().split()]
def LI_(): return [int(x)-1 for x in sys.stdin.readline().split()]
def LF(): return [float(x) for x in sys.stdin.readline().split()]
def LS(): return sys.stdin.readline().split()
def I(): return int(sys.stdin.readline())
def F(): return float(sys.stdin.readline())
def S(): return input()
def pf(s): return print(s, flush=True)
def main():
rr = []
def f(n):
pa = LI()
da = LI()
e = collections.defaultdict(list)
for i in range(n-1):
a = i + 2
b = pa[i]
d = da[i]
e[a].append((b,d))
e[b].append((a,d))
rf = collections.defaultdict(bool)
s = None
for k,v in e.items():
if len(v) == 1:
rf[k] = True
else:
s = k
r = 0
for k,v in e.items():
for l,d in v:
if k > l:
continue
if rf[k] or rf[l]:
r += d
else:
r += d * 3
def search(s):
d = collections.defaultdict(lambda: inf)
d[s] = 0
q = []
heapq.heappush(q, (0, s))
v = collections.defaultdict(bool)
while len(q):
k, u = heapq.heappop(q)
if v[u]:
continue
v[u] = True
for uv, ud in e[u]:
if v[uv] or rf[uv]:
continue
vd = k + ud
if d[uv] > vd:
d[uv] = vd
heapq.heappush(q, (vd, uv))
return d
sd = search(s)
sm = max(sd.values())
for k,v in sd.items():
if v == sm:
s = k
sd = search(s)
sm = max(sd.values())
return r - sm
while 1:
n = I()
if n == 0:
break
rr.append(f(n))
return '\n'.join(map(str,rr))
print(main())
``` | output | 1 | 72,447 | 1 | 144,895 |
Provide a correct Python 3 solution for this coding contest problem.
Bridge Removal
ICPC islands once had been a popular tourist destination. For nature preservation, however, the government decided to prohibit entrance to the islands, and to remove all the man-made structures there. The hardest part of the project is to remove all the bridges connecting the islands.
There are n islands and n-1 bridges. The bridges are built so that all the islands are reachable from all the other islands by crossing one or more bridges. The bridge removal team can choose any island as the starting point, and can repeat either of the following steps.
* Move to another island by crossing a bridge that is connected to the current island.
* Remove one bridge that is connected to the current island, and stay at the same island after the removal.
Of course, a bridge, once removed, cannot be crossed in either direction. Crossing or removing a bridge both takes time proportional to the length of the bridge. Your task is to compute the shortest time necessary for removing all the bridges. Note that the island where the team starts can differ from where the team finishes the work.
Input
The input consists of at most 100 datasets. Each dataset is formatted as follows.
> n
> p2 p3 ... pn
> d2 d3 ... dn
The first integer n (3 ≤ n ≤ 800) is the number of the islands. The islands are numbered from 1 to n. The second line contains n-1 island numbers pi (1 ≤ pi < i), and tells that for each i from 2 to n the island i and the island pi are connected by a bridge. The third line contains n-1 integers di (1 ≤ di ≤ 100,000) each denoting the length of the corresponding bridge. That is, the length of the bridge connecting the island i and pi is di. It takes di units of time to cross the bridge, and also the same units of time to remove it. Note that, with this input format, it is assured that all the islands are reachable each other by crossing one or more bridges.
The input ends with a line with a single zero.
Output
For each dataset, print the minimum time units required to remove all the bridges in a single line. Each line should not have any character other than this number.
Sample Input
4
1 2 3
10 20 30
10
1 2 2 1 5 5 1 8 8
10 1 1 20 1 1 30 1 1
3
1 1
1 1
0
Output for the Sample Input
80
136
2
Example
Input
4
1 2 3
10 20 30
10
1 2 2 1 5 5 1 8 8
10 1 1 20 1 1 30 1 1
3
1 1
1 1
0
Output
80
136
2 | instruction | 0 | 72,448 | 1 | 144,896 |
"Correct Solution:
```
while True:
n = int(input())
if n == 0:break
plst = list(map(int, input().split()))
dlst = list(map(int, input().split()))
edges = [[] for _ in range(n)]
for i in range(1, n):
edges[i].append((plst[i - 1] - 1, dlst[i - 1]))
edges[plst[i - 1] - 1].append((i, dlst[i - 1]))
is_leaf = [len(edges[i]) == 1 for i in range(n)]
INF = 10 ** 20
def dist(x):
dist_from_x = [-INF] * n
dist_from_x[x] = 0
checked = [False] * n
checked[x] = True
def search(x):
for to, d in edges[x]:
if is_leaf[to] or checked[to]:continue
checked[to] = True
dist_from_x[to] = dist_from_x[x] + d
search(to)
search(x)
return dist_from_x
for i in range(n):
if not is_leaf[i]:
dist_from_s = dist(i)
break
u = dist_from_s.index(max(dist_from_s))
dist_from_u = dist(u)
dia = max(dist_from_u)
v = dist_from_u.index(dia)
ans = sum(dlst) * 3
for i in range(n):
if len(edges[i]) == 1:
ans -= edges[i][0][1] * 2
print(ans - dia)
``` | output | 1 | 72,448 | 1 | 144,897 |
Provide a correct Python 3 solution for this coding contest problem.
Bridge Removal
ICPC islands once had been a popular tourist destination. For nature preservation, however, the government decided to prohibit entrance to the islands, and to remove all the man-made structures there. The hardest part of the project is to remove all the bridges connecting the islands.
There are n islands and n-1 bridges. The bridges are built so that all the islands are reachable from all the other islands by crossing one or more bridges. The bridge removal team can choose any island as the starting point, and can repeat either of the following steps.
* Move to another island by crossing a bridge that is connected to the current island.
* Remove one bridge that is connected to the current island, and stay at the same island after the removal.
Of course, a bridge, once removed, cannot be crossed in either direction. Crossing or removing a bridge both takes time proportional to the length of the bridge. Your task is to compute the shortest time necessary for removing all the bridges. Note that the island where the team starts can differ from where the team finishes the work.
Input
The input consists of at most 100 datasets. Each dataset is formatted as follows.
> n
> p2 p3 ... pn
> d2 d3 ... dn
The first integer n (3 ≤ n ≤ 800) is the number of the islands. The islands are numbered from 1 to n. The second line contains n-1 island numbers pi (1 ≤ pi < i), and tells that for each i from 2 to n the island i and the island pi are connected by a bridge. The third line contains n-1 integers di (1 ≤ di ≤ 100,000) each denoting the length of the corresponding bridge. That is, the length of the bridge connecting the island i and pi is di. It takes di units of time to cross the bridge, and also the same units of time to remove it. Note that, with this input format, it is assured that all the islands are reachable each other by crossing one or more bridges.
The input ends with a line with a single zero.
Output
For each dataset, print the minimum time units required to remove all the bridges in a single line. Each line should not have any character other than this number.
Sample Input
4
1 2 3
10 20 30
10
1 2 2 1 5 5 1 8 8
10 1 1 20 1 1 30 1 1
3
1 1
1 1
0
Output for the Sample Input
80
136
2
Example
Input
4
1 2 3
10 20 30
10
1 2 2 1 5 5 1 8 8
10 1 1 20 1 1 30 1 1
3
1 1
1 1
0
Output
80
136
2 | instruction | 0 | 72,449 | 1 | 144,898 |
"Correct Solution:
```
def solve():
from collections import deque
def bfs(start):
q = deque()
q.append(start)
unvisited = [True] * (n + 1)
unvisited[start] = False
distances = [0] * (n + 1)
while q:
x = q.popleft()
for i, d in adj_list[x]:
if unvisited[i]:
q.append(i)
unvisited[i] = False
distances[i] = distances[x] + d
max_d = max(distances)
return (distances.index(max_d), max_d)
import sys
file_input = sys.stdin
while True:
n = int(file_input.readline())
if n == 0:
break
p = list(map(int, file_input.readline().split()))
d = list(map(int, file_input.readline().split()))
end_bridges_weight = 0
adj_list = [[] for i in range(n + 1)]
s = 0
for i1, i2, b_l in zip(range(2, n + 1), p, d):
if i1 not in p[i1-1:]:
end_bridges_weight += b_l
else:
s = i1
adj_list[i1].append((i2, b_l))
adj_list[i2].append((i1, b_l))
if p.count(1) == 1:
del adj_list[2][0]
end_bridges_weight += d[0]
e, dm = bfs(s)
e, dm = bfs(e)
ans = sum(d) * 3 - end_bridges_weight * 2 - dm
print(ans)
solve()
``` | output | 1 | 72,449 | 1 | 144,899 |
Provide a correct Python 3 solution for this coding contest problem.
Bridge Removal
ICPC islands once had been a popular tourist destination. For nature preservation, however, the government decided to prohibit entrance to the islands, and to remove all the man-made structures there. The hardest part of the project is to remove all the bridges connecting the islands.
There are n islands and n-1 bridges. The bridges are built so that all the islands are reachable from all the other islands by crossing one or more bridges. The bridge removal team can choose any island as the starting point, and can repeat either of the following steps.
* Move to another island by crossing a bridge that is connected to the current island.
* Remove one bridge that is connected to the current island, and stay at the same island after the removal.
Of course, a bridge, once removed, cannot be crossed in either direction. Crossing or removing a bridge both takes time proportional to the length of the bridge. Your task is to compute the shortest time necessary for removing all the bridges. Note that the island where the team starts can differ from where the team finishes the work.
Input
The input consists of at most 100 datasets. Each dataset is formatted as follows.
> n
> p2 p3 ... pn
> d2 d3 ... dn
The first integer n (3 ≤ n ≤ 800) is the number of the islands. The islands are numbered from 1 to n. The second line contains n-1 island numbers pi (1 ≤ pi < i), and tells that for each i from 2 to n the island i and the island pi are connected by a bridge. The third line contains n-1 integers di (1 ≤ di ≤ 100,000) each denoting the length of the corresponding bridge. That is, the length of the bridge connecting the island i and pi is di. It takes di units of time to cross the bridge, and also the same units of time to remove it. Note that, with this input format, it is assured that all the islands are reachable each other by crossing one or more bridges.
The input ends with a line with a single zero.
Output
For each dataset, print the minimum time units required to remove all the bridges in a single line. Each line should not have any character other than this number.
Sample Input
4
1 2 3
10 20 30
10
1 2 2 1 5 5 1 8 8
10 1 1 20 1 1 30 1 1
3
1 1
1 1
0
Output for the Sample Input
80
136
2
Example
Input
4
1 2 3
10 20 30
10
1 2 2 1 5 5 1 8 8
10 1 1 20 1 1 30 1 1
3
1 1
1 1
0
Output
80
136
2 | instruction | 0 | 72,450 | 1 | 144,900 |
"Correct Solution:
```
from collections import defaultdict, deque
while 1:
n = int(input())
if n == 0:
break
p = list(map(int, input().split()))
d = list(map(int, input().split()))
dic = defaultdict(int)
tree = [[] for i in range(n)]
for i in range(n - 1):
tree[i + 1].append(p[i]- 1)
tree[p[i] - 1].append(i + 1)
dic[(i + 1, p[i] - 1)] = d[i]
dic[(p[i] - 1, i + 1)] = d[i]
ans = 0
de = []
for num,i in enumerate(tree):
if len(i) == 1:
de.append((num,i[0]))
for num, di in de:
tree[num].remove(di)
tree[di].remove(num)
ans += dic[(num, di)]
b = 0
for i in range(n):
check = [True] * n
q = deque()
q.append((i, 0))
check[i] = False
while q:
now, di = q.pop()
b = max(b, di)
for k in tree[now]:
if check[k]:
check[k] = False
q.append((k, di + dic[k, now]))
print(sum(d)*3-2*ans-b)
``` | output | 1 | 72,450 | 1 | 144,901 |
Provide a correct Python 3 solution for this coding contest problem.
Bridge Removal
ICPC islands once had been a popular tourist destination. For nature preservation, however, the government decided to prohibit entrance to the islands, and to remove all the man-made structures there. The hardest part of the project is to remove all the bridges connecting the islands.
There are n islands and n-1 bridges. The bridges are built so that all the islands are reachable from all the other islands by crossing one or more bridges. The bridge removal team can choose any island as the starting point, and can repeat either of the following steps.
* Move to another island by crossing a bridge that is connected to the current island.
* Remove one bridge that is connected to the current island, and stay at the same island after the removal.
Of course, a bridge, once removed, cannot be crossed in either direction. Crossing or removing a bridge both takes time proportional to the length of the bridge. Your task is to compute the shortest time necessary for removing all the bridges. Note that the island where the team starts can differ from where the team finishes the work.
Input
The input consists of at most 100 datasets. Each dataset is formatted as follows.
> n
> p2 p3 ... pn
> d2 d3 ... dn
The first integer n (3 ≤ n ≤ 800) is the number of the islands. The islands are numbered from 1 to n. The second line contains n-1 island numbers pi (1 ≤ pi < i), and tells that for each i from 2 to n the island i and the island pi are connected by a bridge. The third line contains n-1 integers di (1 ≤ di ≤ 100,000) each denoting the length of the corresponding bridge. That is, the length of the bridge connecting the island i and pi is di. It takes di units of time to cross the bridge, and also the same units of time to remove it. Note that, with this input format, it is assured that all the islands are reachable each other by crossing one or more bridges.
The input ends with a line with a single zero.
Output
For each dataset, print the minimum time units required to remove all the bridges in a single line. Each line should not have any character other than this number.
Sample Input
4
1 2 3
10 20 30
10
1 2 2 1 5 5 1 8 8
10 1 1 20 1 1 30 1 1
3
1 1
1 1
0
Output for the Sample Input
80
136
2
Example
Input
4
1 2 3
10 20 30
10
1 2 2 1 5 5 1 8 8
10 1 1 20 1 1 30 1 1
3
1 1
1 1
0
Output
80
136
2 | instruction | 0 | 72,451 | 1 | 144,902 |
"Correct Solution:
```
from heapq import heappush, heappop
def dijkstra(s):
d = [float("inf") for i in range(n)]
d[s] = 0
q = [(0,s)]
while q:
dx,x = heappop(q)
for y,c in v[x]:
if f[y] > 1:
if dx+c < d[y]:
d[y] = dx+c
heappush(q,(d[y],y))
return [-1 if d[i] == float("inf") else d[i] for i in range(n)]
while 1:
n = int(input())
if n == 0:
break
p = list(map(int,input().split()))
d = list(map(int,input().split()))
v = [[] for i in range(n)]
edge = [None for i in range(n-1)]
f = [0 for i in range(n)]
for i in range(1,n):
j = p[i-1]-1
c = d[i-1]
edge[i-1] = [j,i]
v[i].append((j,c))
v[j].append((i,c))
f[i] += 1
f[j] += 1
ans = 0
for x in range(n-1):
i,j = edge[x]
if f[i] == 1 or f[j] == 1:
ans += d[x]
else:
ans += 3*d[x]
dist = dijkstra(0)
md = max(dist)
l = dist.index(md)
dist = dijkstra(l)
m = max(dist)
print(ans-m)
``` | output | 1 | 72,451 | 1 | 144,903 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Bridge Removal
ICPC islands once had been a popular tourist destination. For nature preservation, however, the government decided to prohibit entrance to the islands, and to remove all the man-made structures there. The hardest part of the project is to remove all the bridges connecting the islands.
There are n islands and n-1 bridges. The bridges are built so that all the islands are reachable from all the other islands by crossing one or more bridges. The bridge removal team can choose any island as the starting point, and can repeat either of the following steps.
* Move to another island by crossing a bridge that is connected to the current island.
* Remove one bridge that is connected to the current island, and stay at the same island after the removal.
Of course, a bridge, once removed, cannot be crossed in either direction. Crossing or removing a bridge both takes time proportional to the length of the bridge. Your task is to compute the shortest time necessary for removing all the bridges. Note that the island where the team starts can differ from where the team finishes the work.
Input
The input consists of at most 100 datasets. Each dataset is formatted as follows.
> n
> p2 p3 ... pn
> d2 d3 ... dn
The first integer n (3 ≤ n ≤ 800) is the number of the islands. The islands are numbered from 1 to n. The second line contains n-1 island numbers pi (1 ≤ pi < i), and tells that for each i from 2 to n the island i and the island pi are connected by a bridge. The third line contains n-1 integers di (1 ≤ di ≤ 100,000) each denoting the length of the corresponding bridge. That is, the length of the bridge connecting the island i and pi is di. It takes di units of time to cross the bridge, and also the same units of time to remove it. Note that, with this input format, it is assured that all the islands are reachable each other by crossing one or more bridges.
The input ends with a line with a single zero.
Output
For each dataset, print the minimum time units required to remove all the bridges in a single line. Each line should not have any character other than this number.
Sample Input
4
1 2 3
10 20 30
10
1 2 2 1 5 5 1 8 8
10 1 1 20 1 1 30 1 1
3
1 1
1 1
0
Output for the Sample Input
80
136
2
Example
Input
4
1 2 3
10 20 30
10
1 2 2 1 5 5 1 8 8
10 1 1 20 1 1 30 1 1
3
1 1
1 1
0
Output
80
136
2
Submitted Solution:
```
def solve():
from collections import deque
def dfs(start, turn=False):
path = deque()
path.append(start)
bridge_lengths = deque()
bridge_lengths.append(0)
unvisited = [True] * (n + 1)
unvisited[start] = False
rest = n - 1
diameter = 0
while True:
u = path[-1]
for i, d in adj_list[u]:
if unvisited[i]:
path.append(i)
unvisited[i] = False
rest -= 1
bridge_lengths.append(d)
break
else:
distance = sum(bridge_lengths)
if diameter < distance:
diameter = distance
ans = diameter - bridge_lengths[1] - bridge_lengths[-1]
end_point = u
if rest == 0:
break
path.pop()
bridge_lengths.pop()
if turn:
return ans
else:
return end_point
import sys
file_input = sys.stdin
while True:
n = int(file_input.readline())
if n == 0:
break
p = list(map(int, file_input.readline().split()))
d = list(map(int, file_input.readline().split()))
adj_list = [[] for i in range(n + 1)]
end_bridges_weight = 0
for i1, i2, b_l in zip(range(2, n + 1), p, d):
adj_list[i1].append((i2, b_l))
adj_list[i2].append((i1, b_l))
if i1 not in p[i1-1:]:
end_bridges_weight += b_l
if p.count(1) == 1:
end_bridges_weight += d[0]
e = dfs(1)
d_m = dfs(e, turn=True)
ans = sum(d) * 3 - end_bridges_weight * 2 - d_m
print(ans)
solve()
``` | instruction | 0 | 72,452 | 1 | 144,904 |
No | output | 1 | 72,452 | 1 | 144,905 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Bridge Removal
ICPC islands once had been a popular tourist destination. For nature preservation, however, the government decided to prohibit entrance to the islands, and to remove all the man-made structures there. The hardest part of the project is to remove all the bridges connecting the islands.
There are n islands and n-1 bridges. The bridges are built so that all the islands are reachable from all the other islands by crossing one or more bridges. The bridge removal team can choose any island as the starting point, and can repeat either of the following steps.
* Move to another island by crossing a bridge that is connected to the current island.
* Remove one bridge that is connected to the current island, and stay at the same island after the removal.
Of course, a bridge, once removed, cannot be crossed in either direction. Crossing or removing a bridge both takes time proportional to the length of the bridge. Your task is to compute the shortest time necessary for removing all the bridges. Note that the island where the team starts can differ from where the team finishes the work.
Input
The input consists of at most 100 datasets. Each dataset is formatted as follows.
> n
> p2 p3 ... pn
> d2 d3 ... dn
The first integer n (3 ≤ n ≤ 800) is the number of the islands. The islands are numbered from 1 to n. The second line contains n-1 island numbers pi (1 ≤ pi < i), and tells that for each i from 2 to n the island i and the island pi are connected by a bridge. The third line contains n-1 integers di (1 ≤ di ≤ 100,000) each denoting the length of the corresponding bridge. That is, the length of the bridge connecting the island i and pi is di. It takes di units of time to cross the bridge, and also the same units of time to remove it. Note that, with this input format, it is assured that all the islands are reachable each other by crossing one or more bridges.
The input ends with a line with a single zero.
Output
For each dataset, print the minimum time units required to remove all the bridges in a single line. Each line should not have any character other than this number.
Sample Input
4
1 2 3
10 20 30
10
1 2 2 1 5 5 1 8 8
10 1 1 20 1 1 30 1 1
3
1 1
1 1
0
Output for the Sample Input
80
136
2
Example
Input
4
1 2 3
10 20 30
10
1 2 2 1 5 5 1 8 8
10 1 1 20 1 1 30 1 1
3
1 1
1 1
0
Output
80
136
2
Submitted Solution:
```
def solve():
from collections import deque
def dfs(start, turn=False):
path = deque()
path.append(start)
bridge_lengths = deque()
bridge_lengths.append(0)
unvisited = [True] * (n + 1)
unvisited[start] = False
rest = core_islands_num - 1
diameter = 0
end_point = start
while True:
u = path[-1]
for i, d in adj_list[u]:
if unvisited[i]:
path.append(i)
unvisited[i] = False
rest -= 1
bridge_lengths.append(d)
break
else:
distance = sum(bridge_lengths)
if diameter < distance:
diameter = distance
end_point = u
if rest == 0:
break
path.pop()
bridge_lengths.pop()
if turn:
return diameter
else:
return end_point
import sys
#file_input = sys.stdin
file_input = open("1196_in_1", 'r')#
while True:
n = int(file_input.readline())
if n == 0:
break
p = list(map(int, file_input.readline().split()))
d = list(map(int, file_input.readline().split()))
end_bridges_weight = 0
core_islands_num = n
adj_list = [[] for i in range(n + 1)]
s = 1
for i1, i2, b_l in zip(range(2, n + 1), p, d):
if i1 not in p[i1-1:]:
end_bridges_weight += b_l
core_islands_num -= 1
else:
s = i1
adj_list[i1].append((i2, b_l))
adj_list[i2].append((i1, b_l))
if p.count(1) == 1:
del adj_list[2][0]
end_bridges_weight += d[0]
core_islands_num -= 1
e = dfs(s)
dm = dfs(e, turn=True)
ans = sum(d) * 3 - end_bridges_weight * 2 - dm
print(ans)
solve()
``` | instruction | 0 | 72,453 | 1 | 144,906 |
No | output | 1 | 72,453 | 1 | 144,907 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Bridge Removal
ICPC islands once had been a popular tourist destination. For nature preservation, however, the government decided to prohibit entrance to the islands, and to remove all the man-made structures there. The hardest part of the project is to remove all the bridges connecting the islands.
There are n islands and n-1 bridges. The bridges are built so that all the islands are reachable from all the other islands by crossing one or more bridges. The bridge removal team can choose any island as the starting point, and can repeat either of the following steps.
* Move to another island by crossing a bridge that is connected to the current island.
* Remove one bridge that is connected to the current island, and stay at the same island after the removal.
Of course, a bridge, once removed, cannot be crossed in either direction. Crossing or removing a bridge both takes time proportional to the length of the bridge. Your task is to compute the shortest time necessary for removing all the bridges. Note that the island where the team starts can differ from where the team finishes the work.
Input
The input consists of at most 100 datasets. Each dataset is formatted as follows.
> n
> p2 p3 ... pn
> d2 d3 ... dn
The first integer n (3 ≤ n ≤ 800) is the number of the islands. The islands are numbered from 1 to n. The second line contains n-1 island numbers pi (1 ≤ pi < i), and tells that for each i from 2 to n the island i and the island pi are connected by a bridge. The third line contains n-1 integers di (1 ≤ di ≤ 100,000) each denoting the length of the corresponding bridge. That is, the length of the bridge connecting the island i and pi is di. It takes di units of time to cross the bridge, and also the same units of time to remove it. Note that, with this input format, it is assured that all the islands are reachable each other by crossing one or more bridges.
The input ends with a line with a single zero.
Output
For each dataset, print the minimum time units required to remove all the bridges in a single line. Each line should not have any character other than this number.
Sample Input
4
1 2 3
10 20 30
10
1 2 2 1 5 5 1 8 8
10 1 1 20 1 1 30 1 1
3
1 1
1 1
0
Output for the Sample Input
80
136
2
Example
Input
4
1 2 3
10 20 30
10
1 2 2 1 5 5 1 8 8
10 1 1 20 1 1 30 1 1
3
1 1
1 1
0
Output
80
136
2
Submitted Solution:
```
def dfs(start, frm, edges, mem):
if mem[start]:
return mem[start]
round_trip = 0
for dest, length in edges[start]:
if dest == frm:
continue
dfs(dest, start, edges, mem)
if len(edges[dest]) == 1:
round_trip += length
continue
rt, _ = mem[dest]
round_trip += length + rt + length + length
one_way = round_trip
for dest, length in edges[start]:
if dest == frm:
continue
if len(edges[dest]) == 1:
continue
rt, ow = mem[dest]
one_way = min(one_way, round_trip - rt - length + ow)
mem[start] = (round_trip, one_way)
return round_trip, one_way
def load():
N = int(input())
if N == 0:
return None
Ps = [int(p)-1 for p in input().split()]
Ds = [int(d) for d in input().split()]
edges = [[] for _ in range(N)]
for i in range(N-1):
p = Ps[i]
d = Ds[i]
i += 1
edges[i].append((p, d))
edges[p].append((i, d))
return edges
def solve1(edges):
N = len(edges)
ans = 100000 * 800
for i in range(N):
mem = [None for _ in range(N)]
_, one_way = dfs(i, -1, edges, mem)
ans = min(ans, one_way)
return ans
while True:
edges = load()
if edges is None:
break
print(solve1(edges))
``` | instruction | 0 | 72,454 | 1 | 144,908 |
No | output | 1 | 72,454 | 1 | 144,909 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Bridge Removal
ICPC islands once had been a popular tourist destination. For nature preservation, however, the government decided to prohibit entrance to the islands, and to remove all the man-made structures there. The hardest part of the project is to remove all the bridges connecting the islands.
There are n islands and n-1 bridges. The bridges are built so that all the islands are reachable from all the other islands by crossing one or more bridges. The bridge removal team can choose any island as the starting point, and can repeat either of the following steps.
* Move to another island by crossing a bridge that is connected to the current island.
* Remove one bridge that is connected to the current island, and stay at the same island after the removal.
Of course, a bridge, once removed, cannot be crossed in either direction. Crossing or removing a bridge both takes time proportional to the length of the bridge. Your task is to compute the shortest time necessary for removing all the bridges. Note that the island where the team starts can differ from where the team finishes the work.
Input
The input consists of at most 100 datasets. Each dataset is formatted as follows.
> n
> p2 p3 ... pn
> d2 d3 ... dn
The first integer n (3 ≤ n ≤ 800) is the number of the islands. The islands are numbered from 1 to n. The second line contains n-1 island numbers pi (1 ≤ pi < i), and tells that for each i from 2 to n the island i and the island pi are connected by a bridge. The third line contains n-1 integers di (1 ≤ di ≤ 100,000) each denoting the length of the corresponding bridge. That is, the length of the bridge connecting the island i and pi is di. It takes di units of time to cross the bridge, and also the same units of time to remove it. Note that, with this input format, it is assured that all the islands are reachable each other by crossing one or more bridges.
The input ends with a line with a single zero.
Output
For each dataset, print the minimum time units required to remove all the bridges in a single line. Each line should not have any character other than this number.
Sample Input
4
1 2 3
10 20 30
10
1 2 2 1 5 5 1 8 8
10 1 1 20 1 1 30 1 1
3
1 1
1 1
0
Output for the Sample Input
80
136
2
Example
Input
4
1 2 3
10 20 30
10
1 2 2 1 5 5 1 8 8
10 1 1 20 1 1 30 1 1
3
1 1
1 1
0
Output
80
136
2
Submitted Solution:
```
import time
time.sleep(120)
exit(0)
``` | instruction | 0 | 72,455 | 1 | 144,910 |
No | output | 1 | 72,455 | 1 | 144,911 |
Provide a correct Python 3 solution for this coding contest problem.
Convex polygon pillar industrial city
The Industrial Convex Pillar City (ICPC) is a city of buildings in the shape of several convex polygonal columns. You are about to walk through this city from your current location S to your destination T. The sun is strong today, so I want to go to my destination without passing through the sun as much as possible. If the building is on a straight line connecting the point where you are standing and the sun, you are behind the building and will not be exposed to the sun. Also, since all the outer circumferences of the buildings in this city have eaves, while walking along the outer circumference of the buildings, even if you walk along the edge of the sun, you will not receive the sunlight. You are free to walk around the city anywhere except inside the building.
Create a program that outputs the walking distance of Hinata when walking from the current location to the destination so as not to receive the sun.
<image>
Figure E1: For the first input
<image>
Figure E2: For the second input
<image>
Figure E3: For the third input
Input
The input consists of multiple datasets. The maximum number of data sets does not exceed 30. Each dataset is represented in the following format.
> N
> NV1 H1 X1,1 Y1,1 X1,2 Y1,2 ... X1, NV1 Y1, NV1
> ...
> NVN HN XN, 1 YN, 1 XN, 2 YN, 2 ... XN, NVN YN, NVN
> θ φ
> Sx Sy Tx Ty
>
N in the first line represents the number of buildings. The following N lines specify the shape of each building. NVi represents the number of vertices of the polygon when the i-th building is viewed from above, and Hi represents the height of the i-th building. Xi, j and Yi, j represent the x-coordinate and y-coordinate of the j-th vertex of the polygon when the i-th building is viewed from above. The vertices are given in counterclockwise order. All buildings are convex polygons when viewed from above, and there are no other buildings inside the building, and the vertices and sides do not overlap with other polygons. The following lines are given θ and φ, which represent the direction of the sun, θ represents the direction of the sun as a counterclockwise angle from the positive direction of x, and φ is the elevation angle of the sun from the horizon, that is, looking up at the sun. It represents the angle between the direction of the line of sight and the ground surface. However, the sun is at infinity and does not change its position during movement. The following lines are given the coordinates of the current location and destination, (Sx, Sy) and (Tx, Ty).
> All the numerical values given by the input are integers and satisfy the following conditions.
> 1 ≤ N ≤ 100
> 3 ≤ NVi ≤ 12
> 1 ≤ Hi ≤ 1,000
> 0 ≤ θ <360
> 0 <φ <90
All coordinates are -1,000 or more and 1,000 or less. The current location and the destination are different, and neither exists inside or outside the building.
> The end of the input is represented by a single zero line.
> ### Output
For each dataset, output the shortest walking distance in Hinata on one line. The output must not have an absolute error greater than 0.001.
> ### Sample Input
2
4 1 0 0 1 0 1 1 0 1
4 2 2 2 3 2 3 3 2 3
60 45
-1 -1 4 4
Four
4 1 0 0 3 1 1 2 0 1
3 2 10 7 8 2 12 4
6 8 7 12 8 13 9 15 10 19 11 24 10 25
5 4 16 2 16 4 12 8 14 2 15 0
167 38
3 3 15 21
12
4 3 -8 -3 -9 -3 -9 -5 -8 -6
4 5 -4 -5 -7 -5 -7 -6 -5 -6
4 2 -4 1 -5 1 -5 -4 -4 -4 -4
4 1 -1 1 -2 1 -2 -4 -1 -3
4 2 2 3 -1 3 -2 2 3 2
4 1 3 1 2 1 2 -3 3 -4
4 7 1 0 0 0 0 -1 1 -1
4 4 9 5 7 5 7 4 10 4
4 3 6 5 5 4 5 0 6 0
4 5 8 -1 5 -1 6 -2 8 -2
4 1 10 0 9 0 9 -2 10 -1
4 6 10 2 8 2 8 1 10 1
131 78
-10 10 10 -10
0
Output for Sample Input
1.93185
7.87174
20.86840
Example
Input
2
4 1 0 0 1 0 1 1 0 1
4 2 2 2 3 2 3 3 2 3
60 45
-1 -1 4 4
4
4 1 0 0 3 1 1 2 0 1
3 2 10 7 8 2 12 4
6 8 7 12 8 13 9 15 10 19 11 24 10 25
5 4 16 2 16 4 12 8 14 2 15 0
167 38
3 3 15 21
12
4 3 -8 -3 -9 -3 -9 -5 -8 -6
4 5 -4 -5 -7 -5 -7 -6 -5 -6
4 2 -4 1 -5 1 -5 -4 -4 -4
4 1 -1 1 -2 1 -2 -4 -1 -3
4 2 2 3 -1 3 -2 2 3 2
4 1 3 1 2 1 2 -3 3 -4
4 7 1 0 0 0 0 -1 1 -1
4 4 9 5 7 5 7 4 10 4
4 3 6 5 5 4 5 0 6 0
4 5 8 -1 5 -1 6 -2 8 -2
4 1 10 0 9 0 9 -2 10 -1
4 6 10 2 8 2 8 1 10 1
131 78
-10 10 10 -10
0
Output
1.93185
7.87174
20.86840 | instruction | 0 | 72,458 | 1 | 144,916 |
"Correct Solution:
```
from math import sin, cos, tan, radians
from heapq import heappush, heappop
import sys
readline = sys.stdin.readline
write = sys.stdout.write
def dot3(O, A, B):
ox, oy = O; ax, ay = A; bx, by = B
return (ax - ox) * (bx - ox) + (ay - oy) * (by - oy)
def cross3(O, A, B):
ox, oy = O; ax, ay = A; bx, by = B
return (ax - ox) * (by - oy) - (bx - ox) * (ay - oy)
def dist2(A, B):
ax, ay = A; bx, by = B
return (ax - bx) ** 2 + (ay - by) ** 2
def is_intersection(P0, P1, Q0, Q1):
C0 = cross3(P0, P1, Q0)
C1 = cross3(P0, P1, Q1)
if C0 == C1 == 0:
E0 = dot3(P0, P1, Q0)
E1 = dot3(P0, P1, Q1)
if not E0 < E1:
E0, E1 = E1, E0
return E0 <= dist2(P0, P1) and 0 <= E1
D0 = cross3(Q0, Q1, P0)
D1 = cross3(Q0, Q1, P1)
return C0 * C1 <= 0 and D0 * D1 <= 0
def convex_hull(ps):
qs = []
n = len(ps)
for p in ps:
while len(qs) > 1 and cross3(qs[-1], qs[-2], p) >= 0:
qs.pop()
qs.append(p)
t = len(qs)
for i in range(n-2, -1, -1):
p = ps[i]
while len(qs) > t and cross3(qs[-1], qs[-2], p) >= 0:
qs.pop()
qs.append(p)
return qs
def cross2(p, q):
return p[0]*q[1] - p[1]*q[0]
def dot2(p, q):
return p[0]*q[0] + p[1]*q[1]
def dist1(p):
return p[0]**2 + p[1]**2
def segment_line_dist_d(x, p0, p1):
z0 = (p1[0] - p0[0], p1[1] - p0[1])
z1 = (x[0] - p0[0], x[1] - p0[1])
if 0 <= dot2(z0, z1) <= dist1(z0):
return cross2(z0, z1)**2 / dist1(z0)
z2 = (x[0] - p1[0], x[1] - p1[1])
return min(dist1(z1), dist1(z2))
def polygon_contain(x, ps):
if len(ps) == 1:
return 0
pl = len(ps)
return (
all(cross3(ps[i-1], ps[i], x) > 0 for i in range(pl)) or
all(cross3(ps[i-1], ps[i], x) < 0 for i in range(pl))
)
def convex_polygon_contain(p0, qs):
L = len(qs)
if L < 3:
return False
left = 1; right = L
x0, y0 = q0 = qs[0]
while left+1 < right:
mid = (left + right) >> 1
if cross3(q0, p0, qs[mid]) <= 0:
left = mid
else:
right = mid
if left == L-1:
left -= 1
qi = qs[left]; qj = qs[left+1]
v0 = cross3(q0, qi, qj)
v1 = cross3(q0, p0, qj)
v2 = cross3(q0, qi, p0)
if v0 < 0:
v1 = -v1; v2 = -v2
return 0 <= v1 and 0 <= v2 and v1 + v2 <= v0
def convex_polygons_intersection(ps, qs):
pl = len(ps); ql = len(qs)
if pl == 1 or ql == 1:
return 0
i = j = 0
while (i < pl or j < ql) and (i < 2*pl) and (j < 2*ql):
px0, py0 = ps0 = ps[(i-1)%pl]; px1, py1 = ps1 = ps[i%pl]
qx0, qy0 = qs0 = qs[(j-1)%ql]; qx1, qy1 = qs1 = qs[j%ql]
if is_intersection(ps0, ps1, qs0, qs1):
return 1
ax = px1 - px0; ay = py1 - py0
bx = qx1 - qx0; by = qy1 - qy0
v = (ax*by - bx*ay)
va = cross3(qs0, qs1, ps1)
vb = cross3(ps0, ps1, qs1)
if v == 0 and va < 0 and vb < 0:
return 0
if v == 0 and va == 0 and vb == 0:
i += 1
elif v >= 0:
if vb > 0:
i += 1
else:
j += 1
else:
if va > 0:
j += 1
else:
i += 1
return 0
def find_tangent(p0, qs):
L = len(qs)
d = L//3
gx = (qs[0][0] + qs[d][0] + qs[2*d][0]) / 3
gy = (qs[0][1] + qs[d][1] + qs[2*d][1]) / 3
g = (gx, gy)
ma = -1; mi = 2; k0 = 0; k1 = 0
for i in range(L):
v = cross3(p0, qs[i], g) / (dist2(p0, g) * dist2(p0, qs[i]))**.5
if v > ma:
k1 = i
ma = v
if v < mi:
k0 = i
mi = v
return k0, k1
def tangent_polygon_dist(ps, qs):
Lp = len(ps); Lq = len(qs)
pi, qi = find_tangent(qs[0], ps)
pj, qj = find_tangent(ps[0], qs)
if qi < pi:
qi += Lp
if qj < pj:
qj += Lq
res = dist2(ps[pi], qs[pj])
if pj < qj:
for i in range(pi, qi+1):
x = ps[i-Lp]
for j in range(pj, qj+1):
res = min(res, segment_line_dist_d(x, qs[(j-1)%Lq], qs[j-Lq]))
if pi < qi:
for j in range(pj, qj+1):
x = qs[j-Lq]
for i in range(pi, qi+1):
res = min(res, segment_line_dist_d(x, ps[(i-1)%Lp], ps[i-Lp]))
return res**.5
def polygons_dist(ps, qs):
if (convex_polygons_intersection(ps, qs)
or convex_polygon_contain(ps[0], qs)
or convex_polygon_contain(qs[0], ps)):
return 0
return tangent_polygon_dist(ps, qs)
def solve():
N = int(readline())
if N == 0:
return False
P = [[] for i in range(N)]
H = [0]*N
for i in range(N):
k, h, *ps = map(int, readline().split())
H[i] = h
Pi = P[i]
for j in range(k):
x, y = ps[2*j:2*j+2]
Pi.append((x, y))
theta, phi = map(int, readline().split())
r_theta = radians(theta)
r_phi = radians(90 - phi)
dx = -cos(r_theta)*tan(r_phi)
dy = -sin(r_theta)*tan(r_phi)
sx, sy, tx, ty = map(int, readline().split())
for i in range(N):
Pi = P[i]
hi = H[i]
for j in range(len(Pi)):
x, y = Pi[j]
Pi.append((x + hi*dx, y + hi*dy))
Pi.sort()
P[i] = convex_hull(Pi)[:-1]
#print(P[i])
P.append([(sx, sy)])
P.append([(tx, ty)])
E = [[0]*(N+2) for i in range(N+2)]
dist = [10**18]*(N+2)
for i in range(N+2):
for j in range(i+1, N+2):
E[i][j] = E[j][i] = polygons_dist(P[i], P[j])
que = [(0, N)]
dist[N] = 0
while que:
cost, v = heappop(que)
if dist[v] < cost:
continue
for w in range(N+2):
n_cost = cost + E[v][w]
if n_cost < dist[w]:
dist[w] = n_cost
heappush(que, (n_cost, w))
print("%.16f" % dist[N+1])
return True
while solve():
...
``` | output | 1 | 72,458 | 1 | 144,917 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Alice received a set of Toy Train™ from Bob. It consists of one train and a connected railway network of n stations, enumerated from 1 through n. The train occupies one station at a time and travels around the network of stations in a circular manner. More precisely, the immediate station that the train will visit after station i is station i+1 if 1 ≤ i < n or station 1 if i = n. It takes the train 1 second to travel to its next station as described.
Bob gave Alice a fun task before he left: to deliver m candies that are initially at some stations to their independent destinations using the train. The candies are enumerated from 1 through m. Candy i (1 ≤ i ≤ m), now at station a_i, should be delivered to station b_i (a_i ≠ b_i).
<image> The blue numbers on the candies correspond to b_i values. The image corresponds to the 1-st example.
The train has infinite capacity, and it is possible to load off any number of candies at a station. However, only at most one candy can be loaded from a station onto the train before it leaves the station. You can choose any candy at this station. The time it takes to move the candies is negligible.
Now, Alice wonders how much time is needed for the train to deliver all candies. Your task is to find, for each station, the minimum time the train would need to deliver all the candies were it to start from there.
Input
The first line contains two space-separated integers n and m (2 ≤ n ≤ 5 000; 1 ≤ m ≤ 20 000) — the number of stations and the number of candies, respectively.
The i-th of the following m lines contains two space-separated integers a_i and b_i (1 ≤ a_i, b_i ≤ n; a_i ≠ b_i) — the station that initially contains candy i and the destination station of the candy, respectively.
Output
In the first and only line, print n space-separated integers, the i-th of which is the minimum time, in seconds, the train would need to deliver all the candies were it to start from station i.
Examples
Input
5 7
2 4
5 1
2 3
3 4
4 1
5 3
3 5
Output
10 9 10 10 9
Input
2 3
1 2
1 2
1 2
Output
5 6
Note
Consider the second sample.
If the train started at station 1, the optimal strategy is as follows.
1. Load the first candy onto the train.
2. Proceed to station 2. This step takes 1 second.
3. Deliver the first candy.
4. Proceed to station 1. This step takes 1 second.
5. Load the second candy onto the train.
6. Proceed to station 2. This step takes 1 second.
7. Deliver the second candy.
8. Proceed to station 1. This step takes 1 second.
9. Load the third candy onto the train.
10. Proceed to station 2. This step takes 1 second.
11. Deliver the third candy.
Hence, the train needs 5 seconds to complete the tasks.
If the train were to start at station 2, however, it would need to move to station 1 before it could load the first candy, which would take one additional second. Thus, the answer in this scenario is 5+1 = 6 seconds. | instruction | 0 | 72,535 | 1 | 145,070 |
Tags: brute force, greedy
Correct Solution:
```
import sys
from collections import defaultdict,deque
n,m=map(int,sys.stdin.readline().split())
dist=defaultdict(list)
sweet=defaultdict(list)
for i in range(m):
u,v=map(int,sys.stdin.readline().split())
sweet[u].append(v)
dist[u].append(0)
for i in sweet:
le=len(sweet[i])
for j in range(le):
if sweet[i][j]>=i:
dist[i][j]=sweet[i][j]-i
else:
dist[i][j]=n-(i-sweet[i][j])
dist[i].sort()
#print(dist,'dits')
for i in dist:
count=0
le=len(dist[i])
for k in range(le-1,-1,-1):
dist[i][k]+=count*n
count+=1
dist[i].sort()
vis=defaultdict(int)
for i in dist:
if dist[i]==[]:
vis[i]=0
else:
vis[i]=dist[i][-1]
#print(dist,'dist')
#print(vis,'vis')
ans=[0 for _ in range(n)]
for i in range(1,n+1):
cur=0
#print(i,'i')
for k in range(1,n+1):
new=0
if k>=i:
if vis[k]!=0:
new=vis[k]+k-i
#print(new,'new',k,'k')
else:
if vis[k]!=0:
new=vis[k]+(n)-(i-k)
#print(new,'new',k,'k')
cur=max(cur,new)
ans[i-1]=cur
print(*ans)
``` | output | 1 | 72,535 | 1 | 145,071 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Alice received a set of Toy Train™ from Bob. It consists of one train and a connected railway network of n stations, enumerated from 1 through n. The train occupies one station at a time and travels around the network of stations in a circular manner. More precisely, the immediate station that the train will visit after station i is station i+1 if 1 ≤ i < n or station 1 if i = n. It takes the train 1 second to travel to its next station as described.
Bob gave Alice a fun task before he left: to deliver m candies that are initially at some stations to their independent destinations using the train. The candies are enumerated from 1 through m. Candy i (1 ≤ i ≤ m), now at station a_i, should be delivered to station b_i (a_i ≠ b_i).
<image> The blue numbers on the candies correspond to b_i values. The image corresponds to the 1-st example.
The train has infinite capacity, and it is possible to load off any number of candies at a station. However, only at most one candy can be loaded from a station onto the train before it leaves the station. You can choose any candy at this station. The time it takes to move the candies is negligible.
Now, Alice wonders how much time is needed for the train to deliver all candies. Your task is to find, for each station, the minimum time the train would need to deliver all the candies were it to start from there.
Input
The first line contains two space-separated integers n and m (2 ≤ n ≤ 5 000; 1 ≤ m ≤ 20 000) — the number of stations and the number of candies, respectively.
The i-th of the following m lines contains two space-separated integers a_i and b_i (1 ≤ a_i, b_i ≤ n; a_i ≠ b_i) — the station that initially contains candy i and the destination station of the candy, respectively.
Output
In the first and only line, print n space-separated integers, the i-th of which is the minimum time, in seconds, the train would need to deliver all the candies were it to start from station i.
Examples
Input
5 7
2 4
5 1
2 3
3 4
4 1
5 3
3 5
Output
10 9 10 10 9
Input
2 3
1 2
1 2
1 2
Output
5 6
Note
Consider the second sample.
If the train started at station 1, the optimal strategy is as follows.
1. Load the first candy onto the train.
2. Proceed to station 2. This step takes 1 second.
3. Deliver the first candy.
4. Proceed to station 1. This step takes 1 second.
5. Load the second candy onto the train.
6. Proceed to station 2. This step takes 1 second.
7. Deliver the second candy.
8. Proceed to station 1. This step takes 1 second.
9. Load the third candy onto the train.
10. Proceed to station 2. This step takes 1 second.
11. Deliver the third candy.
Hence, the train needs 5 seconds to complete the tasks.
If the train were to start at station 2, however, it would need to move to station 1 before it could load the first candy, which would take one additional second. Thus, the answer in this scenario is 5+1 = 6 seconds. | instruction | 0 | 72,536 | 1 | 145,072 |
Tags: brute force, greedy
Correct Solution:
```
from sys import stdin
from collections import deque
import heapq
def realDist(n,long):
out = []
dists = [x[0] + x[1] for x in long]
#print(dists)
d2 = [(-1, -1)] + sorted([(dists[x], long[x][0]) for x in range(len(long))])
before = 0
after = d2[-1][0]
ind = 0
for x in range(n):
if ind < len(long):
if long[ind][0] < x:
before = max(before, n-1+long[ind][1])
ind += 1
out.append(max(before,after))
before -= 1
after -= 1
return out
n,m = [int(x) for x in stdin.readline().split()]
candy = {}
long = []
maxLen = 0
for c in range(m):
a,b = [int(x) for x in stdin.readline().split()]
a -= 1
b -= 1
b = (b-a)%n
if a in candy:
heapq.heappush(candy[a],b)
if len(candy[a]) == maxLen:
long.append(a)
elif len(candy[a]) > maxLen:
long = [a]
maxLen = len(candy[a])
else:
candy[a] = [b]
if maxLen == 0:
maxLen = 1
long = [a]
elif maxLen == 1:
long.append(a)
long2 = long[:]
long = [(x+candy[x][0])%n for x in long]
long3 = [(x,candy[x][0]) for x in long2]
long4 = []
for c in candy:
if len(candy[c]) == maxLen-1:
long4.append((c, candy[c][0]))
long.sort()
long2.sort()
long3.sort()
long4.sort()
longSet = set(long)
base = n*maxLen-n
ind = 0
out = [x+base for x in realDist(n,long3)]
out2 = [x+base-n for x in realDist(n,long4)]
out3 = [max(out[x], out2[x]) for x in range(n)]
print(' '.join([str(x) for x in out3]))
``` | output | 1 | 72,536 | 1 | 145,073 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Alice received a set of Toy Train™ from Bob. It consists of one train and a connected railway network of n stations, enumerated from 1 through n. The train occupies one station at a time and travels around the network of stations in a circular manner. More precisely, the immediate station that the train will visit after station i is station i+1 if 1 ≤ i < n or station 1 if i = n. It takes the train 1 second to travel to its next station as described.
Bob gave Alice a fun task before he left: to deliver m candies that are initially at some stations to their independent destinations using the train. The candies are enumerated from 1 through m. Candy i (1 ≤ i ≤ m), now at station a_i, should be delivered to station b_i (a_i ≠ b_i).
<image> The blue numbers on the candies correspond to b_i values. The image corresponds to the 1-st example.
The train has infinite capacity, and it is possible to load off any number of candies at a station. However, only at most one candy can be loaded from a station onto the train before it leaves the station. You can choose any candy at this station. The time it takes to move the candies is negligible.
Now, Alice wonders how much time is needed for the train to deliver all candies. Your task is to find, for each station, the minimum time the train would need to deliver all the candies were it to start from there.
Input
The first line contains two space-separated integers n and m (2 ≤ n ≤ 5 000; 1 ≤ m ≤ 20 000) — the number of stations and the number of candies, respectively.
The i-th of the following m lines contains two space-separated integers a_i and b_i (1 ≤ a_i, b_i ≤ n; a_i ≠ b_i) — the station that initially contains candy i and the destination station of the candy, respectively.
Output
In the first and only line, print n space-separated integers, the i-th of which is the minimum time, in seconds, the train would need to deliver all the candies were it to start from station i.
Examples
Input
5 7
2 4
5 1
2 3
3 4
4 1
5 3
3 5
Output
10 9 10 10 9
Input
2 3
1 2
1 2
1 2
Output
5 6
Note
Consider the second sample.
If the train started at station 1, the optimal strategy is as follows.
1. Load the first candy onto the train.
2. Proceed to station 2. This step takes 1 second.
3. Deliver the first candy.
4. Proceed to station 1. This step takes 1 second.
5. Load the second candy onto the train.
6. Proceed to station 2. This step takes 1 second.
7. Deliver the second candy.
8. Proceed to station 1. This step takes 1 second.
9. Load the third candy onto the train.
10. Proceed to station 2. This step takes 1 second.
11. Deliver the third candy.
Hence, the train needs 5 seconds to complete the tasks.
If the train were to start at station 2, however, it would need to move to station 1 before it could load the first candy, which would take one additional second. Thus, the answer in this scenario is 5+1 = 6 seconds. | instruction | 0 | 72,537 | 1 | 145,074 |
Tags: brute force, greedy
Correct Solution:
```
n,m=map(int,input().split())
stations=[]
for i in range(n):
stations.append([])
for i in range(m):
a,b=map(int,input().split())
stations[a-1].append((b-a)%n)
maxes=[]
for i in range(n):
if len(stations[i])>0:
big=min(stations[i])
else:
big=0
maxes.append(n*max(len(stations[i])-1,0)+big)
out=[]
new=maxes[:]
big=0
for j in range(n):
if new[j]+j>big and new[j]>0:
big=new[j]+j
curr=big
out.append(str(curr))
for i in range(n-1):
if maxes[i]>0:
curr=max(curr-1,maxes[i]+n-1)
else:
curr=curr-1
out.append(str(curr))
print(" ".join(out))
``` | output | 1 | 72,537 | 1 | 145,075 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Alice received a set of Toy Train™ from Bob. It consists of one train and a connected railway network of n stations, enumerated from 1 through n. The train occupies one station at a time and travels around the network of stations in a circular manner. More precisely, the immediate station that the train will visit after station i is station i+1 if 1 ≤ i < n or station 1 if i = n. It takes the train 1 second to travel to its next station as described.
Bob gave Alice a fun task before he left: to deliver m candies that are initially at some stations to their independent destinations using the train. The candies are enumerated from 1 through m. Candy i (1 ≤ i ≤ m), now at station a_i, should be delivered to station b_i (a_i ≠ b_i).
<image> The blue numbers on the candies correspond to b_i values. The image corresponds to the 1-st example.
The train has infinite capacity, and it is possible to load off any number of candies at a station. However, only at most one candy can be loaded from a station onto the train before it leaves the station. You can choose any candy at this station. The time it takes to move the candies is negligible.
Now, Alice wonders how much time is needed for the train to deliver all candies. Your task is to find, for each station, the minimum time the train would need to deliver all the candies were it to start from there.
Input
The first line contains two space-separated integers n and m (2 ≤ n ≤ 5 000; 1 ≤ m ≤ 20 000) — the number of stations and the number of candies, respectively.
The i-th of the following m lines contains two space-separated integers a_i and b_i (1 ≤ a_i, b_i ≤ n; a_i ≠ b_i) — the station that initially contains candy i and the destination station of the candy, respectively.
Output
In the first and only line, print n space-separated integers, the i-th of which is the minimum time, in seconds, the train would need to deliver all the candies were it to start from station i.
Examples
Input
5 7
2 4
5 1
2 3
3 4
4 1
5 3
3 5
Output
10 9 10 10 9
Input
2 3
1 2
1 2
1 2
Output
5 6
Note
Consider the second sample.
If the train started at station 1, the optimal strategy is as follows.
1. Load the first candy onto the train.
2. Proceed to station 2. This step takes 1 second.
3. Deliver the first candy.
4. Proceed to station 1. This step takes 1 second.
5. Load the second candy onto the train.
6. Proceed to station 2. This step takes 1 second.
7. Deliver the second candy.
8. Proceed to station 1. This step takes 1 second.
9. Load the third candy onto the train.
10. Proceed to station 2. This step takes 1 second.
11. Deliver the third candy.
Hence, the train needs 5 seconds to complete the tasks.
If the train were to start at station 2, however, it would need to move to station 1 before it could load the first candy, which would take one additional second. Thus, the answer in this scenario is 5+1 = 6 seconds. | instruction | 0 | 72,538 | 1 | 145,076 |
Tags: brute force, greedy
Correct Solution:
```
# import numpy as np
def dist(a, b):
return (b - a) % n
n, m = list(map(int, input().split(" ")))
sweets = {i: [] for i in range(n)}
for i in range(m):
s, t = list(map(int, input().split(" ")))
sweets[s - 1].append(t - 1)
t = {i: -1e6 for i in range(n)}
for i in range(n):
sweets[i] = sorted(sweets[i], key=lambda x: -dist(i, x))
if len(sweets[i]):
t[i] = (len(sweets[i]) - 1) * n + dist(i, sweets[i][-1])
# t = np.array([t[i] for i in range(n)], dtype=int)
# raise ValueError("")
# print(t)
result = []
m_max, i_max = 0, 0
for i, v in t.items():
if v + i > m_max + i_max:
m_max, i_max = v, i
result.append(m_max + i_max)
for s in range(1, n):
old_max = t[i_max] + dist(s, i_max)
new_max = t[s - 1] + dist(s, s - 1)
if new_max > old_max:
result.append(new_max)
i_max = s - 1
else:
result.append(old_max)
print(" ".join(map(str, result)))
``` | output | 1 | 72,538 | 1 | 145,077 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Alice received a set of Toy Train™ from Bob. It consists of one train and a connected railway network of n stations, enumerated from 1 through n. The train occupies one station at a time and travels around the network of stations in a circular manner. More precisely, the immediate station that the train will visit after station i is station i+1 if 1 ≤ i < n or station 1 if i = n. It takes the train 1 second to travel to its next station as described.
Bob gave Alice a fun task before he left: to deliver m candies that are initially at some stations to their independent destinations using the train. The candies are enumerated from 1 through m. Candy i (1 ≤ i ≤ m), now at station a_i, should be delivered to station b_i (a_i ≠ b_i).
<image> The blue numbers on the candies correspond to b_i values. The image corresponds to the 1-st example.
The train has infinite capacity, and it is possible to load off any number of candies at a station. However, only at most one candy can be loaded from a station onto the train before it leaves the station. You can choose any candy at this station. The time it takes to move the candies is negligible.
Now, Alice wonders how much time is needed for the train to deliver all candies. Your task is to find, for each station, the minimum time the train would need to deliver all the candies were it to start from there.
Input
The first line contains two space-separated integers n and m (2 ≤ n ≤ 5 000; 1 ≤ m ≤ 20 000) — the number of stations and the number of candies, respectively.
The i-th of the following m lines contains two space-separated integers a_i and b_i (1 ≤ a_i, b_i ≤ n; a_i ≠ b_i) — the station that initially contains candy i and the destination station of the candy, respectively.
Output
In the first and only line, print n space-separated integers, the i-th of which is the minimum time, in seconds, the train would need to deliver all the candies were it to start from station i.
Examples
Input
5 7
2 4
5 1
2 3
3 4
4 1
5 3
3 5
Output
10 9 10 10 9
Input
2 3
1 2
1 2
1 2
Output
5 6
Note
Consider the second sample.
If the train started at station 1, the optimal strategy is as follows.
1. Load the first candy onto the train.
2. Proceed to station 2. This step takes 1 second.
3. Deliver the first candy.
4. Proceed to station 1. This step takes 1 second.
5. Load the second candy onto the train.
6. Proceed to station 2. This step takes 1 second.
7. Deliver the second candy.
8. Proceed to station 1. This step takes 1 second.
9. Load the third candy onto the train.
10. Proceed to station 2. This step takes 1 second.
11. Deliver the third candy.
Hence, the train needs 5 seconds to complete the tasks.
If the train were to start at station 2, however, it would need to move to station 1 before it could load the first candy, which would take one additional second. Thus, the answer in this scenario is 5+1 = 6 seconds. | instruction | 0 | 72,539 | 1 | 145,078 |
Tags: brute force, greedy
Correct Solution:
```
#Code by Sounak, IIESTS
#------------------------------warmup----------------------------
import os
import sys
import math
from io import BytesIO, IOBase
from fractions import Fraction
import collections
from itertools import permutations
BUFSIZE = 8192
class FastIO(IOBase):
newlines = 0
def __init__(self, file):
self._fd = file.fileno()
self.buffer = BytesIO()
self.writable = "x" in file.mode or "r" not in file.mode
self.write = self.buffer.write if self.writable else None
def read(self):
while True:
b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
if not b:
break
ptr = self.buffer.tell()
self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr)
self.newlines = 0
return self.buffer.read()
def readline(self):
while self.newlines == 0:
b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
self.newlines = b.count(b"\n") + (not b)
ptr = self.buffer.tell()
self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr)
self.newlines -= 1
return self.buffer.readline()
def flush(self):
if self.writable:
os.write(self._fd, self.buffer.getvalue())
self.buffer.truncate(0), self.buffer.seek(0)
class IOWrapper(IOBase):
def __init__(self, file):
self.buffer = FastIO(file)
self.flush = self.buffer.flush
self.writable = self.buffer.writable
self.write = lambda s: self.buffer.write(s.encode("ascii"))
self.read = lambda: self.buffer.read().decode("ascii")
self.readline = lambda: self.buffer.readline().decode("ascii")
sys.stdin, sys.stdout = IOWrapper(sys.stdin), IOWrapper(sys.stdout)
input = lambda: sys.stdin.readline().rstrip("\r\n")
#-------------------game starts now-----------------------------------------------------
mii=lambda:map(int,input().split())
n,m=mii()
a=[0 for _ in range(n)]
c=[123456 for _ in range(n)]
for _ in range(m):
u,v=mii()
u%=n
v%=n
if v<u: v+=n
a[u]+=1
if c[u]>v: c[u]=v
ans=[]
for i in list(range(1,n))+[0]:
out=0
for j in range(i,n):
if not a[j]: continue
tmp=(j-i)+(a[j]-1)*n+(c[j]-j)
out=max(out,tmp)
#print(1,i,j,tmp)
for j in range(i):
if not a[j]: continue
tmp=(j+n-i)+(a[j]-1)*n+(c[j]-j)
out=max(out,tmp)
#print(2,i,j,tmp)
ans.append(out)
print(" ".join(map(str,ans)))
``` | output | 1 | 72,539 | 1 | 145,079 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.