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.
If the girl doesn't go to Denis, then Denis will go to the girl. Using this rule, the young man left home, bought flowers and went to Nastya.
On the way from Denis's house to the girl's house is a road of n lines. This road can't be always crossed in one green light. Foreseeing this, the good mayor decided to place safety islands in some parts of the road. Each safety island is located after a line, as well as at the beginning and at the end of the road. Pedestrians can relax on them, gain strength and wait for a green light.
Denis came to the edge of the road exactly at the moment when the green light turned on. The boy knows that the traffic light first lights up g seconds green, and then r seconds red, then again g seconds green and so on.
Formally, the road can be represented as a segment [0, n]. Initially, Denis is at point 0. His task is to get to point n in the shortest possible time.
He knows many different integers d_1, d_2, …, d_m, where 0 ≤ d_i ≤ n — are the coordinates of points, in which the safety islands are located. Only at one of these points, the boy can be at a time when the red light is on.
Unfortunately, Denis isn't always able to control himself because of the excitement, so some restrictions are imposed:
* He must always move while the green light is on because it's difficult to stand when so beautiful girl is waiting for you. Denis can change his position by ± 1 in 1 second. While doing so, he must always stay inside the segment [0, n].
* He can change his direction only on the safety islands (because it is safe). This means that if in the previous second the boy changed his position by +1 and he walked on a safety island, then he can change his position by ± 1. Otherwise, he can change his position only by +1. Similarly, if in the previous second he changed his position by -1, on a safety island he can change position by ± 1, and at any other point by -1.
* At the moment when the red light is on, the boy must be on one of the safety islands. He can continue moving in any direction when the green light is on.
Denis has crossed the road as soon as his coordinate becomes equal to n.
This task was not so simple, because it's possible that it is impossible to cross the road. Since Denis has all thoughts about his love, he couldn't solve this problem and asked us to help him. Find the minimal possible time for which he can cross the road according to these rules, or find that it is impossible to do.
Input
The first line contains two integers n and m (1 ≤ n ≤ 10^6, 2 ≤ m ≤ min(n + 1, 10^4)) — road width and the number of safety islands.
The second line contains m distinct integers d_1, d_2, …, d_m (0 ≤ d_i ≤ n) — the points where the safety islands are located. It is guaranteed that there are 0 and n among them.
The third line contains two integers g, r (1 ≤ g, r ≤ 1000) — the time that the green light stays on and the time that the red light stays on.
Output
Output a single integer — the minimum time for which Denis can cross the road with obeying all the rules.
If it is impossible to cross the road output -1.
Examples
Input
15 5
0 3 7 14 15
11 11
Output
45
Input
13 4
0 3 7 13
9 9
Output
-1
Note
In the first test, the optimal route is:
* for the first green light, go to 7 and return to 3. In this case, we will change the direction of movement at the point 7, which is allowed, since there is a safety island at this point. In the end, we will be at the point of 3, where there is also a safety island. The next 11 seconds we have to wait for the red light.
* for the second green light reaches 14. Wait for the red light again.
* for 1 second go to 15. As a result, Denis is at the end of the road.
In total, 45 seconds are obtained.
In the second test, it is impossible to cross the road according to all the rules. | instruction | 0 | 84,380 | 1 | 168,760 |
Tags: dfs and similar, dp, graphs, shortest paths
Correct Solution:
```
'''
from bisect import *
from collections import *
from math import gcd,ceil,sqrt,floor,inf
from heapq import *
from itertools import *
from operator import add,mul,sub,xor,truediv,floordiv
from functools import *'''
#------------------------------------------------------------------------
import os
import sys
from io import BytesIO, IOBase
# region fastio
BUFSIZE = 8192
class FastIO(IOBase):
newlines = 0
def __init__(self, file):
self._fd = file.fileno()
self.buffer = BytesIO()
self.writable = "x" in file.mode or "r" not in file.mode
self.write = self.buffer.write if self.writable else None
def read(self):
while True:
b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
if not b:
break
ptr = self.buffer.tell()
self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr)
self.newlines = 0
return self.buffer.read()
def readline(self):
while self.newlines == 0:
b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
self.newlines = b.count(b"\n") + (not b)
ptr = self.buffer.tell()
self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr)
self.newlines -= 1
return self.buffer.readline()
def flush(self):
if self.writable:
os.write(self._fd, self.buffer.getvalue())
self.buffer.truncate(0), self.buffer.seek(0)
class IOWrapper(IOBase):
def __init__(self, file):
self.buffer = FastIO(file)
self.flush = self.buffer.flush
self.writable = self.buffer.writable
self.write = lambda s: self.buffer.write(s.encode("ascii"))
self.read = lambda: self.buffer.read().decode("ascii")
self.readline = lambda: self.buffer.readline().decode("ascii")
sys.stdin, sys.stdout = IOWrapper(sys.stdin), IOWrapper(sys.stdout)
input = lambda: sys.stdin.readline().rstrip("\r\n")
#------------------------------------------------------------------------
def RL(): return map(int, sys.stdin.readline().rstrip().split())
def RLL(): return list(map(int, sys.stdin.readline().rstrip().split()))
def N(): return int(input())
#------------------------------------------------------------------------
from types import GeneratorType
def bootstrap(f, stack=[]):
def wrappedfunc(*args, **kwargs):
if stack:
return f(*args, **kwargs)
else:
to = f(*args, **kwargs)
while True:
if type(to) is GeneratorType:
stack.append(to)
to = next(to)
else:
stack.pop()
if not stack:
break
to = stack[-1].send(to)
return to
return wrappedfunc
mod=10**9+7
farr=[1]
ifa=[]
def fact(x,mod=0):
if mod:
while x>=len(farr):
farr.append(farr[-1]*len(farr)%mod)
else:
while x>=len(farr):
farr.append(farr[-1]*len(farr))
return farr[x]
def ifact(x,mod):
global ifa
fact(x,mod)
ifa.append(pow(farr[-1],mod-2,mod))
for i in range(x,0,-1):
ifa.append(ifa[-1]*i%mod)
ifa.reverse()
def per(i,j,mod=0):
if i<j: return 0
if not mod:
return fact(i)//fact(i-j)
return farr[i]*ifa[i-j]%mod
def com(i,j,mod=0):
if i<j: return 0
if not mod:
return per(i,j)//fact(j)
return per(i,j,mod)*ifa[j]%mod
def catalan(n):
return com(2*n,n)//(n+1)
def isprime(n):
for i in range(2,int(n**0.5)+1):
if n%i==0:
return False
return True
def floorsum(a,b,c,n):#sum((a*i+b)//c for i in range(n+1))
if a==0:return b//c*(n+1)
if a>=c or b>=c: return floorsum(a%c,b%c,c,n)+b//c*(n+1)+a//c*n*(n+1)//2
m=(a*n+b)//c
return n*m-floorsum(c,c-b-1,a,m-1)
def inverse(a,m):
a%=m
if a<=1: return a
return ((1-inverse(m,a)*m)//a)%m
def lowbit(n):
return n&-n
class BIT:
def __init__(self,arr):
self.arr=arr
self.n=len(arr)-1
def update(self,x,v):
while x<=self.n:
self.arr[x]+=v
x+=x&-x
def query(self,x):
ans=0
while x:
ans+=self.arr[x]
x&=x-1
return ans
class ST:
def __init__(self,arr):#n!=0
n=len(arr)
mx=n.bit_length()#取不到
self.st=[[0]*mx for i in range(n)]
for i in range(n):
self.st[i][0]=arr[i]
for j in range(1,mx):
for i in range(n-(1<<j)+1):
self.st[i][j]=max(self.st[i][j-1],self.st[i+(1<<j-1)][j-1])
def query(self,l,r):
if l>r:return -inf
s=(r+1-l).bit_length()-1
return max(self.st[l][s],self.st[r-(1<<s)+1][s])
class DSU:#容量+路径压缩
def __init__(self,n):
self.c=[-1]*n
def same(self,x,y):
return self.find(x)==self.find(y)
def find(self,x):
if self.c[x]<0:
return x
self.c[x]=self.find(self.c[x])
return self.c[x]
def union(self,u,v):
u,v=self.find(u),self.find(v)
if u==v:
return False
if self.c[u]>self.c[v]:
u,v=v,u
self.c[u]+=self.c[v]
self.c[v]=u
return True
def size(self,x): return -self.c[self.find(x)]
class UFS:#秩+路径
def __init__(self,n):
self.parent=[i for i in range(n)]
self.ranks=[0]*n
def find(self,x):
if x!=self.parent[x]:
self.parent[x]=self.find(self.parent[x])
return self.parent[x]
def union(self,u,v):
pu,pv=self.find(u),self.find(v)
if pu==pv:
return False
if self.ranks[pu]>=self.ranks[pv]:
self.parent[pv]=pu
if self.ranks[pv]==self.ranks[pu]:
self.ranks[pu]+=1
else:
self.parent[pu]=pv
def Prime(n):
c=0
prime=[]
flag=[0]*(n+1)
for i in range(2,n+1):
if not flag[i]:
prime.append(i)
c+=1
for j in range(c):
if i*prime[j]>n: break
flag[i*prime[j]]=prime[j]
if i%prime[j]==0: break
return prime
def dij(s,graph):
d={}
d[s]=0
heap=[(0,s)]
seen=set()
while heap:
dis,u=heappop(heap)
if u in seen:
continue
seen.add(u)
for v,w in graph[u]:
if v not in d or d[v]>d[u]+w:
d[v]=d[u]+w
heappush(heap,(d[v],v))
return d
def GP(it): return [[ch,len(list(g))] for ch,g in groupby(it)]
def lcm(a,b): return a*b//gcd(a,b)
def lis(nums):
res=[]
for k in nums:
i=bisect.bisect_left(res,k)
if i==len(res):
res.append(k)
else:
res[i]=k
return len(res)
def RP(nums):#逆序对
n = len(nums)
s=set(nums)
d={}
for i,k in enumerate(sorted(s),1):
d[k]=i
bi=BIT([0]*(len(s)+1))
ans=0
for i in range(n-1,-1,-1):
ans+=bi.query(d[nums[i]]-1)
bi.update(d[nums[i]],1)
return ans
class DLN:
def __init__(self,val):
self.val=val
self.pre=None
self.next=None
def nb(i,j):
for ni,nj in [[i+1,j],[i-1,j],[i,j-1],[i,j+1]]:
if 0<=ni<n and 0<=nj<m:
yield ni,nj
def topo(n):
q=deque()
res=[]
for i in range(1,n+1):
if ind[i]==0:
q.append(i)
res.append(i)
while q:
u=q.popleft()
for v in g[u]:
ind[v]-=1
if ind[v]==0:
q.append(v)
res.append(v)
return res
@bootstrap
def gdfs(r,p):
if len(g[r])==1 and p!=-1:
yield None
for ch in g[r]:
if ch!=p:
yield gdfs(ch,r)
yield None
from collections import deque
t=1
for i in range(t):
n,m=RL()
d=RLL()
inf=10**9
d=[-inf]+sorted(d)+[inf]
g,r=RL()
q=deque([(1,0)])
vis=[0]*((m+1)*g)
dis=[inf]*((m+1)*g)
vis[0]=1
dis[0]=0
cur=0
ans=inf
f=False
while q:
nq=deque()
while q:
u,t=q.popleft()
if u==m:
if t!=0:
ans=min(ans,cur*(g+r)+t)
else:
ans=min(ans,cur*g+(cur-1)*r)
f=True
continue
if t+d[u]-d[u-1]<g and not vis[(u-2)*g+t+d[u]-d[u-1]]:
vis[(u-2)*g+t+d[u]-d[u-1]]=1
q.append((u-1,t+d[u]-d[u-1]))
elif t+d[u]-d[u-1]==g and not vis[(u-2)*g]:
vis[(u-2)*g]=1
nq.append((u-1,0))
if t-d[u]+d[u+1]<g and not vis[u*g+t-d[u]+d[u+1]]:
vis[u*g+t-d[u]+d[u+1]]=1
q.append((u+1,t-d[u]+d[u+1]))
elif t-d[u]+d[u+1]==g and not vis[u*g]:
vis[u*g]=1
nq.append((u+1,0))
#print(q)
#print('nq',nq)
if f:
print(ans)
exit()
q=nq
cur+=1
print(-1)
'''
sys.setrecursionlimit(200000)
import threading
threading.stack_size(10**8)
t=threading.Thr
ead(target=main)
t.start()
t.join()
'''
'''
sys.setrecursionlimit(200000)
import threading
threading.stack_size(10**8)
t=threading.Thread(target=main)
t.start()
t.join()
'''
``` | output | 1 | 84,380 | 1 | 168,761 |
Provide tags and a correct Python 3 solution for this coding contest problem.
If the girl doesn't go to Denis, then Denis will go to the girl. Using this rule, the young man left home, bought flowers and went to Nastya.
On the way from Denis's house to the girl's house is a road of n lines. This road can't be always crossed in one green light. Foreseeing this, the good mayor decided to place safety islands in some parts of the road. Each safety island is located after a line, as well as at the beginning and at the end of the road. Pedestrians can relax on them, gain strength and wait for a green light.
Denis came to the edge of the road exactly at the moment when the green light turned on. The boy knows that the traffic light first lights up g seconds green, and then r seconds red, then again g seconds green and so on.
Formally, the road can be represented as a segment [0, n]. Initially, Denis is at point 0. His task is to get to point n in the shortest possible time.
He knows many different integers d_1, d_2, …, d_m, where 0 ≤ d_i ≤ n — are the coordinates of points, in which the safety islands are located. Only at one of these points, the boy can be at a time when the red light is on.
Unfortunately, Denis isn't always able to control himself because of the excitement, so some restrictions are imposed:
* He must always move while the green light is on because it's difficult to stand when so beautiful girl is waiting for you. Denis can change his position by ± 1 in 1 second. While doing so, he must always stay inside the segment [0, n].
* He can change his direction only on the safety islands (because it is safe). This means that if in the previous second the boy changed his position by +1 and he walked on a safety island, then he can change his position by ± 1. Otherwise, he can change his position only by +1. Similarly, if in the previous second he changed his position by -1, on a safety island he can change position by ± 1, and at any other point by -1.
* At the moment when the red light is on, the boy must be on one of the safety islands. He can continue moving in any direction when the green light is on.
Denis has crossed the road as soon as his coordinate becomes equal to n.
This task was not so simple, because it's possible that it is impossible to cross the road. Since Denis has all thoughts about his love, he couldn't solve this problem and asked us to help him. Find the minimal possible time for which he can cross the road according to these rules, or find that it is impossible to do.
Input
The first line contains two integers n and m (1 ≤ n ≤ 10^6, 2 ≤ m ≤ min(n + 1, 10^4)) — road width and the number of safety islands.
The second line contains m distinct integers d_1, d_2, …, d_m (0 ≤ d_i ≤ n) — the points where the safety islands are located. It is guaranteed that there are 0 and n among them.
The third line contains two integers g, r (1 ≤ g, r ≤ 1000) — the time that the green light stays on and the time that the red light stays on.
Output
Output a single integer — the minimum time for which Denis can cross the road with obeying all the rules.
If it is impossible to cross the road output -1.
Examples
Input
15 5
0 3 7 14 15
11 11
Output
45
Input
13 4
0 3 7 13
9 9
Output
-1
Note
In the first test, the optimal route is:
* for the first green light, go to 7 and return to 3. In this case, we will change the direction of movement at the point 7, which is allowed, since there is a safety island at this point. In the end, we will be at the point of 3, where there is also a safety island. The next 11 seconds we have to wait for the red light.
* for the second green light reaches 14. Wait for the red light again.
* for 1 second go to 15. As a result, Denis is at the end of the road.
In total, 45 seconds are obtained.
In the second test, it is impossible to cross the road according to all the rules. | instruction | 0 | 84,381 | 1 | 168,762 |
Tags: dfs and similar, dp, graphs, shortest paths
Correct Solution:
```
import collections
n,m=map(int,input().split())
arr=list(map(int,input().split()))
arr=sorted(arr)
g,r=map(int,input().split())
q=collections.deque()
q.append((0,0,0))
checked=[[-1]*(g) for _ in range(m)]
checked[0][0]=0
while len(q)!=0:
v,t,cnt=q.popleft()
if v!=m-1:
cost1=arr[v+1]-arr[v]
if t+cost1<=g:
if checked[v+1][(t+cost1)%g]==-1:
if t+cost1<g:
q.appendleft((v+1,t+cost1,cnt))
checked[v+1][t+cost1]=cnt
else:
q.append((v+1,0,cnt+1))
checked[v+1][0]=cnt+1
if v!=0:
cost2=arr[v]-arr[v-1]
if t+cost2<=g:
if checked[v-1][(t+cost2)%g]==-1:
if t+cost2<g:
q.appendleft((v-1,t+cost2,cnt))
checked[v-1][t+cost2]=cnt
else:
q.append((v-1,0,cnt+1))
checked[v-1][0]=cnt+1
ans=10**18
for i in range(m):
for j in range(g):
if checked[i][j]==-1:
continue
else:
if j+n-arr[i]<=g:
ans=min(ans,checked[i][j]*(g+r)+j+n-arr[i])
if ans==10**18:
print(-1)
else:
print(ans)
``` | output | 1 | 84,381 | 1 | 168,763 |
Provide tags and a correct Python 3 solution for this coding contest problem.
If the girl doesn't go to Denis, then Denis will go to the girl. Using this rule, the young man left home, bought flowers and went to Nastya.
On the way from Denis's house to the girl's house is a road of n lines. This road can't be always crossed in one green light. Foreseeing this, the good mayor decided to place safety islands in some parts of the road. Each safety island is located after a line, as well as at the beginning and at the end of the road. Pedestrians can relax on them, gain strength and wait for a green light.
Denis came to the edge of the road exactly at the moment when the green light turned on. The boy knows that the traffic light first lights up g seconds green, and then r seconds red, then again g seconds green and so on.
Formally, the road can be represented as a segment [0, n]. Initially, Denis is at point 0. His task is to get to point n in the shortest possible time.
He knows many different integers d_1, d_2, …, d_m, where 0 ≤ d_i ≤ n — are the coordinates of points, in which the safety islands are located. Only at one of these points, the boy can be at a time when the red light is on.
Unfortunately, Denis isn't always able to control himself because of the excitement, so some restrictions are imposed:
* He must always move while the green light is on because it's difficult to stand when so beautiful girl is waiting for you. Denis can change his position by ± 1 in 1 second. While doing so, he must always stay inside the segment [0, n].
* He can change his direction only on the safety islands (because it is safe). This means that if in the previous second the boy changed his position by +1 and he walked on a safety island, then he can change his position by ± 1. Otherwise, he can change his position only by +1. Similarly, if in the previous second he changed his position by -1, on a safety island he can change position by ± 1, and at any other point by -1.
* At the moment when the red light is on, the boy must be on one of the safety islands. He can continue moving in any direction when the green light is on.
Denis has crossed the road as soon as his coordinate becomes equal to n.
This task was not so simple, because it's possible that it is impossible to cross the road. Since Denis has all thoughts about his love, he couldn't solve this problem and asked us to help him. Find the minimal possible time for which he can cross the road according to these rules, or find that it is impossible to do.
Input
The first line contains two integers n and m (1 ≤ n ≤ 10^6, 2 ≤ m ≤ min(n + 1, 10^4)) — road width and the number of safety islands.
The second line contains m distinct integers d_1, d_2, …, d_m (0 ≤ d_i ≤ n) — the points where the safety islands are located. It is guaranteed that there are 0 and n among them.
The third line contains two integers g, r (1 ≤ g, r ≤ 1000) — the time that the green light stays on and the time that the red light stays on.
Output
Output a single integer — the minimum time for which Denis can cross the road with obeying all the rules.
If it is impossible to cross the road output -1.
Examples
Input
15 5
0 3 7 14 15
11 11
Output
45
Input
13 4
0 3 7 13
9 9
Output
-1
Note
In the first test, the optimal route is:
* for the first green light, go to 7 and return to 3. In this case, we will change the direction of movement at the point 7, which is allowed, since there is a safety island at this point. In the end, we will be at the point of 3, where there is also a safety island. The next 11 seconds we have to wait for the red light.
* for the second green light reaches 14. Wait for the red light again.
* for 1 second go to 15. As a result, Denis is at the end of the road.
In total, 45 seconds are obtained.
In the second test, it is impossible to cross the road according to all the rules. | instruction | 0 | 84,382 | 1 | 168,764 |
Tags: dfs and similar, dp, graphs, shortest paths
Correct Solution:
```
from collections import deque
N, M = map(int, input().split())
D = sorted(list(set([int(a) for a in input().split()] + [-1<<10, N])))
M = len(D)
DD = [D[i+1] - D[i] for i in range(M-1)]
green, red = map(int, input().split())
X = [[0] * (green + 1) for _ in range(M)]
Q = deque([(1, green , 0)])
# if tl < green else [(1, green, 1)] if green == tl else [])
ans = 1 << 100
goal = M - 1
while Q:
step, tl, cycles = deque.popleft(Q)
if X[step][tl]: continue
X[step][tl] = 1
if step == goal:
ans = min(ans, cycles * (green + red) + (green - tl if tl < green else -red))
continue
dl, dr = DD[step-1], DD[step]
if dl < tl:
Q.appendleft((step-1, tl - dl, cycles))
elif dl == tl:
Q.append((step-1, green, cycles + 1))
if dr < tl:
Q.appendleft((step+1, tl - dr, cycles))
elif dr == tl:
Q.append((step+1, green, cycles + 1))
print(ans if ans < 1 << 99 else -1)
``` | output | 1 | 84,382 | 1 | 168,765 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
If the girl doesn't go to Denis, then Denis will go to the girl. Using this rule, the young man left home, bought flowers and went to Nastya.
On the way from Denis's house to the girl's house is a road of n lines. This road can't be always crossed in one green light. Foreseeing this, the good mayor decided to place safety islands in some parts of the road. Each safety island is located after a line, as well as at the beginning and at the end of the road. Pedestrians can relax on them, gain strength and wait for a green light.
Denis came to the edge of the road exactly at the moment when the green light turned on. The boy knows that the traffic light first lights up g seconds green, and then r seconds red, then again g seconds green and so on.
Formally, the road can be represented as a segment [0, n]. Initially, Denis is at point 0. His task is to get to point n in the shortest possible time.
He knows many different integers d_1, d_2, …, d_m, where 0 ≤ d_i ≤ n — are the coordinates of points, in which the safety islands are located. Only at one of these points, the boy can be at a time when the red light is on.
Unfortunately, Denis isn't always able to control himself because of the excitement, so some restrictions are imposed:
* He must always move while the green light is on because it's difficult to stand when so beautiful girl is waiting for you. Denis can change his position by ± 1 in 1 second. While doing so, he must always stay inside the segment [0, n].
* He can change his direction only on the safety islands (because it is safe). This means that if in the previous second the boy changed his position by +1 and he walked on a safety island, then he can change his position by ± 1. Otherwise, he can change his position only by +1. Similarly, if in the previous second he changed his position by -1, on a safety island he can change position by ± 1, and at any other point by -1.
* At the moment when the red light is on, the boy must be on one of the safety islands. He can continue moving in any direction when the green light is on.
Denis has crossed the road as soon as his coordinate becomes equal to n.
This task was not so simple, because it's possible that it is impossible to cross the road. Since Denis has all thoughts about his love, he couldn't solve this problem and asked us to help him. Find the minimal possible time for which he can cross the road according to these rules, or find that it is impossible to do.
Input
The first line contains two integers n and m (1 ≤ n ≤ 10^6, 2 ≤ m ≤ min(n + 1, 10^4)) — road width and the number of safety islands.
The second line contains m distinct integers d_1, d_2, …, d_m (0 ≤ d_i ≤ n) — the points where the safety islands are located. It is guaranteed that there are 0 and n among them.
The third line contains two integers g, r (1 ≤ g, r ≤ 1000) — the time that the green light stays on and the time that the red light stays on.
Output
Output a single integer — the minimum time for which Denis can cross the road with obeying all the rules.
If it is impossible to cross the road output -1.
Examples
Input
15 5
0 3 7 14 15
11 11
Output
45
Input
13 4
0 3 7 13
9 9
Output
-1
Note
In the first test, the optimal route is:
* for the first green light, go to 7 and return to 3. In this case, we will change the direction of movement at the point 7, which is allowed, since there is a safety island at this point. In the end, we will be at the point of 3, where there is also a safety island. The next 11 seconds we have to wait for the red light.
* for the second green light reaches 14. Wait for the red light again.
* for 1 second go to 15. As a result, Denis is at the end of the road.
In total, 45 seconds are obtained.
In the second test, it is impossible to cross the road according to all the rules.
Submitted Solution:
```
from collections import deque
N, M = map(int, input().split())
D = sorted(list(set([int(a) for a in input().split()] + [-1<<10, N])))
M = len(D)
DD = [D[i+1] - D[i] for i in range(M-1)]
g, r = map(int, input().split())
X = [[0] * (g + 1) for _ in range(M)]
a = D[1]
Q = deque([(1, g - a, 0)] if a < g else [(1, g, 1)] if g == a else [])
ans = 1 << 100
goal = M - 1
while Q:
i, a, t = deque.popleft(Q)
if X[i][a]: continue
X[i][a] = 1
if i == goal:
ans = min(ans, t * (g + r) + (g - a if a < g else -r))
continue
dl, dr = DD[i-1], DD[i]
if dl < a:
Q.appendleft((i-1, a - dl, t))
elif dl == a:
Q.append((i-1, g, t + 1))
if dr < a:
Q.appendleft((i+1, a - dr, t))
elif dr == a:
Q.append((i+1, g, t + 1))
print(ans if ans < 1 << 99 else -1)
``` | instruction | 0 | 84,383 | 1 | 168,766 |
Yes | output | 1 | 84,383 | 1 | 168,767 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
If the girl doesn't go to Denis, then Denis will go to the girl. Using this rule, the young man left home, bought flowers and went to Nastya.
On the way from Denis's house to the girl's house is a road of n lines. This road can't be always crossed in one green light. Foreseeing this, the good mayor decided to place safety islands in some parts of the road. Each safety island is located after a line, as well as at the beginning and at the end of the road. Pedestrians can relax on them, gain strength and wait for a green light.
Denis came to the edge of the road exactly at the moment when the green light turned on. The boy knows that the traffic light first lights up g seconds green, and then r seconds red, then again g seconds green and so on.
Formally, the road can be represented as a segment [0, n]. Initially, Denis is at point 0. His task is to get to point n in the shortest possible time.
He knows many different integers d_1, d_2, …, d_m, where 0 ≤ d_i ≤ n — are the coordinates of points, in which the safety islands are located. Only at one of these points, the boy can be at a time when the red light is on.
Unfortunately, Denis isn't always able to control himself because of the excitement, so some restrictions are imposed:
* He must always move while the green light is on because it's difficult to stand when so beautiful girl is waiting for you. Denis can change his position by ± 1 in 1 second. While doing so, he must always stay inside the segment [0, n].
* He can change his direction only on the safety islands (because it is safe). This means that if in the previous second the boy changed his position by +1 and he walked on a safety island, then he can change his position by ± 1. Otherwise, he can change his position only by +1. Similarly, if in the previous second he changed his position by -1, on a safety island he can change position by ± 1, and at any other point by -1.
* At the moment when the red light is on, the boy must be on one of the safety islands. He can continue moving in any direction when the green light is on.
Denis has crossed the road as soon as his coordinate becomes equal to n.
This task was not so simple, because it's possible that it is impossible to cross the road. Since Denis has all thoughts about his love, he couldn't solve this problem and asked us to help him. Find the minimal possible time for which he can cross the road according to these rules, or find that it is impossible to do.
Input
The first line contains two integers n and m (1 ≤ n ≤ 10^6, 2 ≤ m ≤ min(n + 1, 10^4)) — road width and the number of safety islands.
The second line contains m distinct integers d_1, d_2, …, d_m (0 ≤ d_i ≤ n) — the points where the safety islands are located. It is guaranteed that there are 0 and n among them.
The third line contains two integers g, r (1 ≤ g, r ≤ 1000) — the time that the green light stays on and the time that the red light stays on.
Output
Output a single integer — the minimum time for which Denis can cross the road with obeying all the rules.
If it is impossible to cross the road output -1.
Examples
Input
15 5
0 3 7 14 15
11 11
Output
45
Input
13 4
0 3 7 13
9 9
Output
-1
Note
In the first test, the optimal route is:
* for the first green light, go to 7 and return to 3. In this case, we will change the direction of movement at the point 7, which is allowed, since there is a safety island at this point. In the end, we will be at the point of 3, where there is also a safety island. The next 11 seconds we have to wait for the red light.
* for the second green light reaches 14. Wait for the red light again.
* for 1 second go to 15. As a result, Denis is at the end of the road.
In total, 45 seconds are obtained.
In the second test, it is impossible to cross the road according to all the rules.
Submitted Solution:
```
INF = float('inf')
from collections import deque
N, M = map(int, input().split())
D = list(sorted([-INF] + list(map(int, input().split()))))
M = len(D)
DD = [D[i+1] - D[i] for i in range(M-1)]
green, red = map(int, input().split())
X = [[0] * (green + 1) for _ in range(M)]
Q = deque([(1, green , 0)])
ans = 1 << 100
goal = M - 1
while Q:
step, tl, cycles = deque.popleft(Q)
if X[step][tl]: continue
X[step][tl] = 1
if step == goal:
ans = min(ans, cycles * (green + red) + (green - tl if tl < green else -red))
continue
dl, dr = DD[step-1], DD[step]
if dl < tl:
Q.appendleft((step-1, tl - dl, cycles))
elif dl == tl:
Q.append((step-1, green, cycles + 1))
if dr < tl:
Q.appendleft((step+1, tl - dr, cycles))
elif dr == tl:
Q.append((step+1, green, cycles + 1))
print(ans if ans < 1 << 99 else -1)
``` | instruction | 0 | 84,384 | 1 | 168,768 |
Yes | output | 1 | 84,384 | 1 | 168,769 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
If the girl doesn't go to Denis, then Denis will go to the girl. Using this rule, the young man left home, bought flowers and went to Nastya.
On the way from Denis's house to the girl's house is a road of n lines. This road can't be always crossed in one green light. Foreseeing this, the good mayor decided to place safety islands in some parts of the road. Each safety island is located after a line, as well as at the beginning and at the end of the road. Pedestrians can relax on them, gain strength and wait for a green light.
Denis came to the edge of the road exactly at the moment when the green light turned on. The boy knows that the traffic light first lights up g seconds green, and then r seconds red, then again g seconds green and so on.
Formally, the road can be represented as a segment [0, n]. Initially, Denis is at point 0. His task is to get to point n in the shortest possible time.
He knows many different integers d_1, d_2, …, d_m, where 0 ≤ d_i ≤ n — are the coordinates of points, in which the safety islands are located. Only at one of these points, the boy can be at a time when the red light is on.
Unfortunately, Denis isn't always able to control himself because of the excitement, so some restrictions are imposed:
* He must always move while the green light is on because it's difficult to stand when so beautiful girl is waiting for you. Denis can change his position by ± 1 in 1 second. While doing so, he must always stay inside the segment [0, n].
* He can change his direction only on the safety islands (because it is safe). This means that if in the previous second the boy changed his position by +1 and he walked on a safety island, then he can change his position by ± 1. Otherwise, he can change his position only by +1. Similarly, if in the previous second he changed his position by -1, on a safety island he can change position by ± 1, and at any other point by -1.
* At the moment when the red light is on, the boy must be on one of the safety islands. He can continue moving in any direction when the green light is on.
Denis has crossed the road as soon as his coordinate becomes equal to n.
This task was not so simple, because it's possible that it is impossible to cross the road. Since Denis has all thoughts about his love, he couldn't solve this problem and asked us to help him. Find the minimal possible time for which he can cross the road according to these rules, or find that it is impossible to do.
Input
The first line contains two integers n and m (1 ≤ n ≤ 10^6, 2 ≤ m ≤ min(n + 1, 10^4)) — road width and the number of safety islands.
The second line contains m distinct integers d_1, d_2, …, d_m (0 ≤ d_i ≤ n) — the points where the safety islands are located. It is guaranteed that there are 0 and n among them.
The third line contains two integers g, r (1 ≤ g, r ≤ 1000) — the time that the green light stays on and the time that the red light stays on.
Output
Output a single integer — the minimum time for which Denis can cross the road with obeying all the rules.
If it is impossible to cross the road output -1.
Examples
Input
15 5
0 3 7 14 15
11 11
Output
45
Input
13 4
0 3 7 13
9 9
Output
-1
Note
In the first test, the optimal route is:
* for the first green light, go to 7 and return to 3. In this case, we will change the direction of movement at the point 7, which is allowed, since there is a safety island at this point. In the end, we will be at the point of 3, where there is also a safety island. The next 11 seconds we have to wait for the red light.
* for the second green light reaches 14. Wait for the red light again.
* for 1 second go to 15. As a result, Denis is at the end of the road.
In total, 45 seconds are obtained.
In the second test, it is impossible to cross the road according to all the rules.
Submitted Solution:
```
import sys
input = sys.stdin.readline
from collections import deque
from typing import List
############ ---- Input Functions ---- ############
def inp():
return(int(input()))
def inlt():
return(list(map(int,input().split())))
def insr():
s = input()
return(list(s[:len(s) - 1]))
def invr():
return(map(int,input().split()))
def compute(n, m, g, r, A: List[int]):
A.sort()
WHITE = -1
GREY = -2
states = [[WHITE] * (g+1) for _ in range(m)]
states[0][g] = 0
states[0][0] = 0
q = deque([(0, g)])
def process_neib(ineib, gneib):
if states[ineib][gneib] != WHITE:
#print(f"Skipped as grey")
return
if ineib == m-1:
#no need to wait there
states[ineib][gneib] = states[index][g_left]
#print(f"Final state dist is {states[ineib][gneib]}")
elif gneib == 0:
states[ineib][gneib] = states[index][g_left] + 1
states[ineib][g] = states[ineib][gneib]
gneib = g
q.append((ineib, gneib))
#print(f"appended right with distance {states[ineib][0]}")
else:
states[ineib][gneib] = states[index][g_left]
q.appendleft((ineib, gneib))
while q:
# sit for this is known
#print(f"Queue is {[(A[i], t) for i,t in q]}")
index, g_left = q.popleft()
#print(f"Popped {A[index], g_left}. Dist is {states[index][g_left]}")
#neib = get_neib(index, g_left, A)
#print(f"Neighbors are {[(A[i], t) for i, t in neib]}")
if index > 0:
# there exists a next one
delta = A[index] - A[index-1]
if g_left >= delta:
process_neib(index-1, g_left-delta)
if index < m-1:
delta = A[index+1] - A[index]
if g_left >= delta:
process_neib(index+1, g_left-delta)
#print(f"appended left with distance {states[ineib][gneib]}")
res = float('inf')
for g_left in range(g):
if states[m-1][g_left] >= 0:
res = min(res, states[m-1][g_left] * (r+g) + g-g_left)
if res != float('inf'):
print(res)
else:
print('-1')
def from_file(f):
return f.readline
# with open('52.txt') as f:
# input = from_file(f)
n, m = invr()
A = inlt()
g,r = invr()
compute(n, m, g, r, A)
``` | instruction | 0 | 84,385 | 1 | 168,770 |
Yes | output | 1 | 84,385 | 1 | 168,771 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
If the girl doesn't go to Denis, then Denis will go to the girl. Using this rule, the young man left home, bought flowers and went to Nastya.
On the way from Denis's house to the girl's house is a road of n lines. This road can't be always crossed in one green light. Foreseeing this, the good mayor decided to place safety islands in some parts of the road. Each safety island is located after a line, as well as at the beginning and at the end of the road. Pedestrians can relax on them, gain strength and wait for a green light.
Denis came to the edge of the road exactly at the moment when the green light turned on. The boy knows that the traffic light first lights up g seconds green, and then r seconds red, then again g seconds green and so on.
Formally, the road can be represented as a segment [0, n]. Initially, Denis is at point 0. His task is to get to point n in the shortest possible time.
He knows many different integers d_1, d_2, …, d_m, where 0 ≤ d_i ≤ n — are the coordinates of points, in which the safety islands are located. Only at one of these points, the boy can be at a time when the red light is on.
Unfortunately, Denis isn't always able to control himself because of the excitement, so some restrictions are imposed:
* He must always move while the green light is on because it's difficult to stand when so beautiful girl is waiting for you. Denis can change his position by ± 1 in 1 second. While doing so, he must always stay inside the segment [0, n].
* He can change his direction only on the safety islands (because it is safe). This means that if in the previous second the boy changed his position by +1 and he walked on a safety island, then he can change his position by ± 1. Otherwise, he can change his position only by +1. Similarly, if in the previous second he changed his position by -1, on a safety island he can change position by ± 1, and at any other point by -1.
* At the moment when the red light is on, the boy must be on one of the safety islands. He can continue moving in any direction when the green light is on.
Denis has crossed the road as soon as his coordinate becomes equal to n.
This task was not so simple, because it's possible that it is impossible to cross the road. Since Denis has all thoughts about his love, he couldn't solve this problem and asked us to help him. Find the minimal possible time for which he can cross the road according to these rules, or find that it is impossible to do.
Input
The first line contains two integers n and m (1 ≤ n ≤ 10^6, 2 ≤ m ≤ min(n + 1, 10^4)) — road width and the number of safety islands.
The second line contains m distinct integers d_1, d_2, …, d_m (0 ≤ d_i ≤ n) — the points where the safety islands are located. It is guaranteed that there are 0 and n among them.
The third line contains two integers g, r (1 ≤ g, r ≤ 1000) — the time that the green light stays on and the time that the red light stays on.
Output
Output a single integer — the minimum time for which Denis can cross the road with obeying all the rules.
If it is impossible to cross the road output -1.
Examples
Input
15 5
0 3 7 14 15
11 11
Output
45
Input
13 4
0 3 7 13
9 9
Output
-1
Note
In the first test, the optimal route is:
* for the first green light, go to 7 and return to 3. In this case, we will change the direction of movement at the point 7, which is allowed, since there is a safety island at this point. In the end, we will be at the point of 3, where there is also a safety island. The next 11 seconds we have to wait for the red light.
* for the second green light reaches 14. Wait for the red light again.
* for 1 second go to 15. As a result, Denis is at the end of the road.
In total, 45 seconds are obtained.
In the second test, it is impossible to cross the road according to all the rules.
Submitted Solution:
```
from collections import deque
N, M = map(int, input().split())
D = sorted(list(set([int(a) for a in input().split()] + [-1<<10, N])))
M = len(D)
DD = [D[i+1] - D[i] for i in range(M-1)]
g, r = map(int, input().split())
X = [[0] * (g + 1) for _ in range(M)]
a = D[1]
Q = deque([(1, g - a, 0)] if a < g else [(1, g, 1)] if g == a else [])
ans = 1 << 100
goal = M - 1
while Q:
i, a, t = deque.popleft(Q)
if X[i][a]: continue
X[i][a] = 1
if i == goal:
ans = min(ans, t * (g + r) + (g - a))
continue
if not a:
a = g
t += 1
dl, dr = DD[i-1], DD[i]
if dl <= a:
Q.appendleft((i-1, a - dl, t))
if dr <= a:
Q.appendleft((i+1, a - dr, t))
print(ans if ans < 1 << 99 else -1)
``` | instruction | 0 | 84,386 | 1 | 168,772 |
No | output | 1 | 84,386 | 1 | 168,773 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
If the girl doesn't go to Denis, then Denis will go to the girl. Using this rule, the young man left home, bought flowers and went to Nastya.
On the way from Denis's house to the girl's house is a road of n lines. This road can't be always crossed in one green light. Foreseeing this, the good mayor decided to place safety islands in some parts of the road. Each safety island is located after a line, as well as at the beginning and at the end of the road. Pedestrians can relax on them, gain strength and wait for a green light.
Denis came to the edge of the road exactly at the moment when the green light turned on. The boy knows that the traffic light first lights up g seconds green, and then r seconds red, then again g seconds green and so on.
Formally, the road can be represented as a segment [0, n]. Initially, Denis is at point 0. His task is to get to point n in the shortest possible time.
He knows many different integers d_1, d_2, …, d_m, where 0 ≤ d_i ≤ n — are the coordinates of points, in which the safety islands are located. Only at one of these points, the boy can be at a time when the red light is on.
Unfortunately, Denis isn't always able to control himself because of the excitement, so some restrictions are imposed:
* He must always move while the green light is on because it's difficult to stand when so beautiful girl is waiting for you. Denis can change his position by ± 1 in 1 second. While doing so, he must always stay inside the segment [0, n].
* He can change his direction only on the safety islands (because it is safe). This means that if in the previous second the boy changed his position by +1 and he walked on a safety island, then he can change his position by ± 1. Otherwise, he can change his position only by +1. Similarly, if in the previous second he changed his position by -1, on a safety island he can change position by ± 1, and at any other point by -1.
* At the moment when the red light is on, the boy must be on one of the safety islands. He can continue moving in any direction when the green light is on.
Denis has crossed the road as soon as his coordinate becomes equal to n.
This task was not so simple, because it's possible that it is impossible to cross the road. Since Denis has all thoughts about his love, he couldn't solve this problem and asked us to help him. Find the minimal possible time for which he can cross the road according to these rules, or find that it is impossible to do.
Input
The first line contains two integers n and m (1 ≤ n ≤ 10^6, 2 ≤ m ≤ min(n + 1, 10^4)) — road width and the number of safety islands.
The second line contains m distinct integers d_1, d_2, …, d_m (0 ≤ d_i ≤ n) — the points where the safety islands are located. It is guaranteed that there are 0 and n among them.
The third line contains two integers g, r (1 ≤ g, r ≤ 1000) — the time that the green light stays on and the time that the red light stays on.
Output
Output a single integer — the minimum time for which Denis can cross the road with obeying all the rules.
If it is impossible to cross the road output -1.
Examples
Input
15 5
0 3 7 14 15
11 11
Output
45
Input
13 4
0 3 7 13
9 9
Output
-1
Note
In the first test, the optimal route is:
* for the first green light, go to 7 and return to 3. In this case, we will change the direction of movement at the point 7, which is allowed, since there is a safety island at this point. In the end, we will be at the point of 3, where there is also a safety island. The next 11 seconds we have to wait for the red light.
* for the second green light reaches 14. Wait for the red light again.
* for 1 second go to 15. As a result, Denis is at the end of the road.
In total, 45 seconds are obtained.
In the second test, it is impossible to cross the road according to all the rules.
Submitted Solution:
```
import collections
n,m=map(int,input().split())
arr=list(map(int,input().split()))
G=[[] for _ in range(m)]
for i in range(m):
if i==0:
G[i].append((i+1,arr[i+1]-arr[i]))
elif i==m-1:
G[i].append((i-1,arr[i]-arr[i-1]))
else:
G[i].append((i-1,arr[i]-arr[i-1]))
G[i].append((i+1,arr[i+1]-arr[i]))
g,r=map(int,input().split())
q=collections.deque()
q.append((0,0,0))
checked=[[0]*(g) for _ in range(m)]
checked[0][0]=1
while len(q)!=0:
v,t,cnt=q.popleft()
if arr[v]==n:
print(cnt*(g+r)+t)
break
for u,cost in G[v]:
if checked[u][t]==0:
checked[u][t]=1
if t+cost<g:
q.append((u,t+cost,cnt))
elif t+cost==g:
q.append((u,0,cnt+1))
else:
print(-1)
``` | instruction | 0 | 84,387 | 1 | 168,774 |
No | output | 1 | 84,387 | 1 | 168,775 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
If the girl doesn't go to Denis, then Denis will go to the girl. Using this rule, the young man left home, bought flowers and went to Nastya.
On the way from Denis's house to the girl's house is a road of n lines. This road can't be always crossed in one green light. Foreseeing this, the good mayor decided to place safety islands in some parts of the road. Each safety island is located after a line, as well as at the beginning and at the end of the road. Pedestrians can relax on them, gain strength and wait for a green light.
Denis came to the edge of the road exactly at the moment when the green light turned on. The boy knows that the traffic light first lights up g seconds green, and then r seconds red, then again g seconds green and so on.
Formally, the road can be represented as a segment [0, n]. Initially, Denis is at point 0. His task is to get to point n in the shortest possible time.
He knows many different integers d_1, d_2, …, d_m, where 0 ≤ d_i ≤ n — are the coordinates of points, in which the safety islands are located. Only at one of these points, the boy can be at a time when the red light is on.
Unfortunately, Denis isn't always able to control himself because of the excitement, so some restrictions are imposed:
* He must always move while the green light is on because it's difficult to stand when so beautiful girl is waiting for you. Denis can change his position by ± 1 in 1 second. While doing so, he must always stay inside the segment [0, n].
* He can change his direction only on the safety islands (because it is safe). This means that if in the previous second the boy changed his position by +1 and he walked on a safety island, then he can change his position by ± 1. Otherwise, he can change his position only by +1. Similarly, if in the previous second he changed his position by -1, on a safety island he can change position by ± 1, and at any other point by -1.
* At the moment when the red light is on, the boy must be on one of the safety islands. He can continue moving in any direction when the green light is on.
Denis has crossed the road as soon as his coordinate becomes equal to n.
This task was not so simple, because it's possible that it is impossible to cross the road. Since Denis has all thoughts about his love, he couldn't solve this problem and asked us to help him. Find the minimal possible time for which he can cross the road according to these rules, or find that it is impossible to do.
Input
The first line contains two integers n and m (1 ≤ n ≤ 10^6, 2 ≤ m ≤ min(n + 1, 10^4)) — road width and the number of safety islands.
The second line contains m distinct integers d_1, d_2, …, d_m (0 ≤ d_i ≤ n) — the points where the safety islands are located. It is guaranteed that there are 0 and n among them.
The third line contains two integers g, r (1 ≤ g, r ≤ 1000) — the time that the green light stays on and the time that the red light stays on.
Output
Output a single integer — the minimum time for which Denis can cross the road with obeying all the rules.
If it is impossible to cross the road output -1.
Examples
Input
15 5
0 3 7 14 15
11 11
Output
45
Input
13 4
0 3 7 13
9 9
Output
-1
Note
In the first test, the optimal route is:
* for the first green light, go to 7 and return to 3. In this case, we will change the direction of movement at the point 7, which is allowed, since there is a safety island at this point. In the end, we will be at the point of 3, where there is also a safety island. The next 11 seconds we have to wait for the red light.
* for the second green light reaches 14. Wait for the red light again.
* for 1 second go to 15. As a result, Denis is at the end of the road.
In total, 45 seconds are obtained.
In the second test, it is impossible to cross the road according to all the rules.
Submitted Solution:
```
"""
NTC here
"""
#!/usr/bin/env python
import os
import sys
from io import BytesIO, IOBase
def iin(): return int(input())
def lin(): return list(map(int, input().split()))
dc = {0:int('1110111', 2), 1:int("0010010", 2), 2:int("1011101", 2), 3:int("1011011", 2), 4:int("0111010", 2), 5:int("1101011", 2), 6:int("1101111", 2), 7:int("1010010", 2), 8:int("1111111", 2), 9:int("1111011", 2)}
def main():
T = 1
for _ in range(T):
n, m = lin()
isl = lin()
isl.sort()
g, r = lin()
ans = [-1]*m
ans[0] = 0
for i in range(m):
if ans[i]==-1:continue
for j in range(i+1, m):
x = (isl[j]-isl[i])
if x>g:break
if (g-x)%2==0:
x1 = ans[i]+(g+r if isl[j]!=n else x)
if ans[j]>-1:
ans[j] = min(ans[j], x1)
else:
ans[j] = x1
print(ans[m-1])
# region fastio
BUFSIZE = 8192
class FastIO(IOBase):
newlines = 0
def __init__(self, file):
self._fd = file.fileno()
self.buffer = BytesIO()
self.writable = "x" in file.mode or "r" not in file.mode
self.write = self.buffer.write if self.writable else None
def read(self):
while True:
b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
if not b:
break
ptr = self.buffer.tell()
self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr)
self.newlines = 0
return self.buffer.read()
def readline(self):
while self.newlines == 0:
b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
self.newlines = b.count(b"\n") + (not b)
ptr = self.buffer.tell()
self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr)
self.newlines -= 1
return self.buffer.readline()
def flush(self):
if self.writable:
os.write(self._fd, self.buffer.getvalue())
self.buffer.truncate(0), self.buffer.seek(0)
class IOWrapper(IOBase):
def __init__(self, file):
self.buffer = FastIO(file)
self.flush = self.buffer.flush
self.writable = self.buffer.writable
self.write = lambda s: self.buffer.write(s.encode("ascii"))
self.read = lambda: self.buffer.read().decode("ascii")
self.readline = lambda: self.buffer.readline().decode("ascii")
sys.stdin, sys.stdout = IOWrapper(sys.stdin), IOWrapper(sys.stdout)
input = lambda: sys.stdin.readline().rstrip("\r\n")
# endregion
if __name__ == "__main__":
main()
``` | instruction | 0 | 84,388 | 1 | 168,776 |
No | output | 1 | 84,388 | 1 | 168,777 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
If the girl doesn't go to Denis, then Denis will go to the girl. Using this rule, the young man left home, bought flowers and went to Nastya.
On the way from Denis's house to the girl's house is a road of n lines. This road can't be always crossed in one green light. Foreseeing this, the good mayor decided to place safety islands in some parts of the road. Each safety island is located after a line, as well as at the beginning and at the end of the road. Pedestrians can relax on them, gain strength and wait for a green light.
Denis came to the edge of the road exactly at the moment when the green light turned on. The boy knows that the traffic light first lights up g seconds green, and then r seconds red, then again g seconds green and so on.
Formally, the road can be represented as a segment [0, n]. Initially, Denis is at point 0. His task is to get to point n in the shortest possible time.
He knows many different integers d_1, d_2, …, d_m, where 0 ≤ d_i ≤ n — are the coordinates of points, in which the safety islands are located. Only at one of these points, the boy can be at a time when the red light is on.
Unfortunately, Denis isn't always able to control himself because of the excitement, so some restrictions are imposed:
* He must always move while the green light is on because it's difficult to stand when so beautiful girl is waiting for you. Denis can change his position by ± 1 in 1 second. While doing so, he must always stay inside the segment [0, n].
* He can change his direction only on the safety islands (because it is safe). This means that if in the previous second the boy changed his position by +1 and he walked on a safety island, then he can change his position by ± 1. Otherwise, he can change his position only by +1. Similarly, if in the previous second he changed his position by -1, on a safety island he can change position by ± 1, and at any other point by -1.
* At the moment when the red light is on, the boy must be on one of the safety islands. He can continue moving in any direction when the green light is on.
Denis has crossed the road as soon as his coordinate becomes equal to n.
This task was not so simple, because it's possible that it is impossible to cross the road. Since Denis has all thoughts about his love, he couldn't solve this problem and asked us to help him. Find the minimal possible time for which he can cross the road according to these rules, or find that it is impossible to do.
Input
The first line contains two integers n and m (1 ≤ n ≤ 10^6, 2 ≤ m ≤ min(n + 1, 10^4)) — road width and the number of safety islands.
The second line contains m distinct integers d_1, d_2, …, d_m (0 ≤ d_i ≤ n) — the points where the safety islands are located. It is guaranteed that there are 0 and n among them.
The third line contains two integers g, r (1 ≤ g, r ≤ 1000) — the time that the green light stays on and the time that the red light stays on.
Output
Output a single integer — the minimum time for which Denis can cross the road with obeying all the rules.
If it is impossible to cross the road output -1.
Examples
Input
15 5
0 3 7 14 15
11 11
Output
45
Input
13 4
0 3 7 13
9 9
Output
-1
Note
In the first test, the optimal route is:
* for the first green light, go to 7 and return to 3. In this case, we will change the direction of movement at the point 7, which is allowed, since there is a safety island at this point. In the end, we will be at the point of 3, where there is also a safety island. The next 11 seconds we have to wait for the red light.
* for the second green light reaches 14. Wait for the red light again.
* for 1 second go to 15. As a result, Denis is at the end of the road.
In total, 45 seconds are obtained.
In the second test, it is impossible to cross the road according to all the rules.
Submitted Solution:
```
import math
def time_calc(cood,g,l,time,r):
flag=0
while(cood<len(l)):
f=0
#print("initial coordinate",cood)
if(g>=(len(l)-cood-1)):
time+=len(l)-cood-1
flag=1
return(time)
while(g-f>0):
#print("g-f:",g-f,"f",f)
if(l[cood+g-2*f:cood+g-2*f+1]==[1]):
if(l[cood-f-len(l):cood-f-1-len(l)]==[1] or l[cood+g-f:cood+g-f+1]==[1]):
# print(l[cood+g-f:cood+g-f+1],cood+g-f,cood+g-f+1)
time= time+g+r
#print("time:",time)
break
f+=2
cood+=g-2*f
if(g-(2*f)<=0):
return(-1)
return(time)
n,s=map(int,input().split())
l=list(map(int,input().split()))
g,r=map(int,input().split())
axis=[]
for i in range(n+1):
axis.append(0)
for make in l:
axis[make]=1
time=0
#print(axis)
print(time_calc(0,g,axis,time,r))
``` | instruction | 0 | 84,389 | 1 | 168,778 |
No | output | 1 | 84,389 | 1 | 168,779 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Barney lives in country USC (United States of Charzeh). USC has n cities numbered from 1 through n and n - 1 roads between them. Cities and roads of USC form a rooted tree (Barney's not sure why it is rooted). Root of the tree is the city number 1. Thus if one will start his journey from city 1, he can visit any city he wants by following roads.
<image>
Some girl has stolen Barney's heart, and Barney wants to find her. He starts looking for in the root of the tree and (since he is Barney Stinson not a random guy), he uses a random DFS to search in the cities. A pseudo code of this algorithm is as follows:
let starting_time be an array of length n
current_time = 0
dfs(v):
current_time = current_time + 1
starting_time[v] = current_time
shuffle children[v] randomly (each permutation with equal possibility)
// children[v] is vector of children cities of city v
for u in children[v]:
dfs(u)
As told before, Barney will start his journey in the root of the tree (equivalent to call dfs(1)).
Now Barney needs to pack a backpack and so he wants to know more about his upcoming journey: for every city i, Barney wants to know the expected value of starting_time[i]. He's a friend of Jon Snow and knows nothing, that's why he asked for your help.
Input
The first line of input contains a single integer n (1 ≤ n ≤ 105) — the number of cities in USC.
The second line contains n - 1 integers p2, p3, ..., pn (1 ≤ pi < i), where pi is the number of the parent city of city number i in the tree, meaning there is a road between cities numbered pi and i in USC.
Output
In the first and only line of output print n numbers, where i-th number is the expected value of starting_time[i].
Your answer for each city will be considered correct if its absolute or relative error does not exceed 10 - 6.
Examples
Input
7
1 2 1 1 4 4
Output
1.0 4.0 5.0 3.5 4.5 5.0 5.0
Input
12
1 1 2 2 4 4 3 3 1 10 8
Output
1.0 5.0 5.5 6.5 7.5 8.0 8.0 7.0 7.5 6.5 7.5 8.0 | instruction | 0 | 84,658 | 1 | 169,316 |
Tags: dfs and similar, math, probabilities, trees
Correct Solution:
```
n = int(input())
pos, tree, ans, sz = list(map(int,input().split())) if n > 1 else [],[],[],[]
for i in range(n):
tree.append([])
ans.append(0.0)
sz.append(0)
for i in range(n - 1):
tree[pos[i] - 1].append(i + 1)
for i in range(n)[::-1]:
sz[i] = 1
for to in tree[i]:
sz[i] += sz[to]
for i in range(n):
for to in tree[i]:
ans[to] = ans[i] + 1 + (sz[i] - 1 - sz[to]) * 0.5
st = lambda i: str(i + 1)
print(' '.join(list(map(st, ans))))
# Made By Mostafa_Khaled
``` | output | 1 | 84,658 | 1 | 169,317 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Barney lives in country USC (United States of Charzeh). USC has n cities numbered from 1 through n and n - 1 roads between them. Cities and roads of USC form a rooted tree (Barney's not sure why it is rooted). Root of the tree is the city number 1. Thus if one will start his journey from city 1, he can visit any city he wants by following roads.
<image>
Some girl has stolen Barney's heart, and Barney wants to find her. He starts looking for in the root of the tree and (since he is Barney Stinson not a random guy), he uses a random DFS to search in the cities. A pseudo code of this algorithm is as follows:
let starting_time be an array of length n
current_time = 0
dfs(v):
current_time = current_time + 1
starting_time[v] = current_time
shuffle children[v] randomly (each permutation with equal possibility)
// children[v] is vector of children cities of city v
for u in children[v]:
dfs(u)
As told before, Barney will start his journey in the root of the tree (equivalent to call dfs(1)).
Now Barney needs to pack a backpack and so he wants to know more about his upcoming journey: for every city i, Barney wants to know the expected value of starting_time[i]. He's a friend of Jon Snow and knows nothing, that's why he asked for your help.
Input
The first line of input contains a single integer n (1 ≤ n ≤ 105) — the number of cities in USC.
The second line contains n - 1 integers p2, p3, ..., pn (1 ≤ pi < i), where pi is the number of the parent city of city number i in the tree, meaning there is a road between cities numbered pi and i in USC.
Output
In the first and only line of output print n numbers, where i-th number is the expected value of starting_time[i].
Your answer for each city will be considered correct if its absolute or relative error does not exceed 10 - 6.
Examples
Input
7
1 2 1 1 4 4
Output
1.0 4.0 5.0 3.5 4.5 5.0 5.0
Input
12
1 1 2 2 4 4 3 3 1 10 8
Output
1.0 5.0 5.5 6.5 7.5 8.0 8.0 7.0 7.5 6.5 7.5 8.0 | instruction | 0 | 84,659 | 1 | 169,318 |
Tags: dfs and similar, math, probabilities, trees
Correct Solution:
```
# [https://gitlab.com/amirmd76/cf-round-362/-/blob/master/B/dans.py <- https://gitlab.com/amirmd76/cf-round-362/tree/master/B <- https://codeforces.com/blog/entry/46031 <- https://codeforces.com/problemset/problem/696/B <- https://algoprog.ru/material/pc696pB]
n = int(input())
if n > 1:
p = input().split(' ')
else:
p = []
g = []
ans = []
sz = []
for i in range(0, n):
g.append([])
ans.append(0.0)
sz.append(0)
for i in range(0, n - 1):
g[int(p[i]) - 1].append(i + 1)
for i in range(0, n)[::-1]:
sz[i] = 1
for to in g[i]:
sz[i] += sz[to]
for i in range(0, n):
for to in g[i]:
ans[to] = ans[i] + 1 + (sz[i] - 1 - sz[to]) * 0.5
print(' '.join([str(a + 1) for a in ans]))
``` | output | 1 | 84,659 | 1 | 169,319 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Barney lives in country USC (United States of Charzeh). USC has n cities numbered from 1 through n and n - 1 roads between them. Cities and roads of USC form a rooted tree (Barney's not sure why it is rooted). Root of the tree is the city number 1. Thus if one will start his journey from city 1, he can visit any city he wants by following roads.
<image>
Some girl has stolen Barney's heart, and Barney wants to find her. He starts looking for in the root of the tree and (since he is Barney Stinson not a random guy), he uses a random DFS to search in the cities. A pseudo code of this algorithm is as follows:
let starting_time be an array of length n
current_time = 0
dfs(v):
current_time = current_time + 1
starting_time[v] = current_time
shuffle children[v] randomly (each permutation with equal possibility)
// children[v] is vector of children cities of city v
for u in children[v]:
dfs(u)
As told before, Barney will start his journey in the root of the tree (equivalent to call dfs(1)).
Now Barney needs to pack a backpack and so he wants to know more about his upcoming journey: for every city i, Barney wants to know the expected value of starting_time[i]. He's a friend of Jon Snow and knows nothing, that's why he asked for your help.
Input
The first line of input contains a single integer n (1 ≤ n ≤ 105) — the number of cities in USC.
The second line contains n - 1 integers p2, p3, ..., pn (1 ≤ pi < i), where pi is the number of the parent city of city number i in the tree, meaning there is a road between cities numbered pi and i in USC.
Output
In the first and only line of output print n numbers, where i-th number is the expected value of starting_time[i].
Your answer for each city will be considered correct if its absolute or relative error does not exceed 10 - 6.
Examples
Input
7
1 2 1 1 4 4
Output
1.0 4.0 5.0 3.5 4.5 5.0 5.0
Input
12
1 1 2 2 4 4 3 3 1 10 8
Output
1.0 5.0 5.5 6.5 7.5 8.0 8.0 7.0 7.5 6.5 7.5 8.0 | instruction | 0 | 84,660 | 1 | 169,320 |
Tags: dfs and similar, math, probabilities, trees
Correct Solution:
```
n = int(input())
if n ==1:
print(1)
exit(0)
l = list(map(int,input().split()))
w = [[]for i in range(n)]
sz = [1]*n
for i in range(n-1):
w[l[i]-1].append(i+1)
for i in range(n-1,-1,-1):
for j in range(len(w[i])):
sz[i]+=sz[w[i][j]]
ans = [0]*n
for i in range(n):
for j in range(len(w[i])):
ans[w[i][j]] = ans[i]+1+(sz[i]-1-sz[w[i][j]])/2
for i in range(n):
print(ans[i]+1,end = " ")
``` | output | 1 | 84,660 | 1 | 169,321 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Barney lives in country USC (United States of Charzeh). USC has n cities numbered from 1 through n and n - 1 roads between them. Cities and roads of USC form a rooted tree (Barney's not sure why it is rooted). Root of the tree is the city number 1. Thus if one will start his journey from city 1, he can visit any city he wants by following roads.
<image>
Some girl has stolen Barney's heart, and Barney wants to find her. He starts looking for in the root of the tree and (since he is Barney Stinson not a random guy), he uses a random DFS to search in the cities. A pseudo code of this algorithm is as follows:
let starting_time be an array of length n
current_time = 0
dfs(v):
current_time = current_time + 1
starting_time[v] = current_time
shuffle children[v] randomly (each permutation with equal possibility)
// children[v] is vector of children cities of city v
for u in children[v]:
dfs(u)
As told before, Barney will start his journey in the root of the tree (equivalent to call dfs(1)).
Now Barney needs to pack a backpack and so he wants to know more about his upcoming journey: for every city i, Barney wants to know the expected value of starting_time[i]. He's a friend of Jon Snow and knows nothing, that's why he asked for your help.
Input
The first line of input contains a single integer n (1 ≤ n ≤ 105) — the number of cities in USC.
The second line contains n - 1 integers p2, p3, ..., pn (1 ≤ pi < i), where pi is the number of the parent city of city number i in the tree, meaning there is a road between cities numbered pi and i in USC.
Output
In the first and only line of output print n numbers, where i-th number is the expected value of starting_time[i].
Your answer for each city will be considered correct if its absolute or relative error does not exceed 10 - 6.
Examples
Input
7
1 2 1 1 4 4
Output
1.0 4.0 5.0 3.5 4.5 5.0 5.0
Input
12
1 1 2 2 4 4 3 3 1 10 8
Output
1.0 5.0 5.5 6.5 7.5 8.0 8.0 7.0 7.5 6.5 7.5 8.0 | instruction | 0 | 84,661 | 1 | 169,322 |
Tags: dfs and similar, math, probabilities, trees
Correct Solution:
```
n = int(input())
pos,tree,ans,sz = list(map(int,input().split())) if n > 1 else [],[],[],[]
for i in range(n):
tree.append([])
ans.append(0.0)
sz.append(0)
for i in range(n-1):
tree[pos[i]-1].append(i+1)
for i in range(n)[::-1]:
sz[i] = 1
for to in tree[i]:
sz[i] += sz[to]
for i in range(n):
for to in tree[i]:
ans[to] = ans[i] + 1 + (sz[i]-1-sz[to]) * 0.5
st = lambda i: str(i+1)
print(' '.join(list(map(st,ans))))
``` | output | 1 | 84,661 | 1 | 169,323 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Barney lives in country USC (United States of Charzeh). USC has n cities numbered from 1 through n and n - 1 roads between them. Cities and roads of USC form a rooted tree (Barney's not sure why it is rooted). Root of the tree is the city number 1. Thus if one will start his journey from city 1, he can visit any city he wants by following roads.
<image>
Some girl has stolen Barney's heart, and Barney wants to find her. He starts looking for in the root of the tree and (since he is Barney Stinson not a random guy), he uses a random DFS to search in the cities. A pseudo code of this algorithm is as follows:
let starting_time be an array of length n
current_time = 0
dfs(v):
current_time = current_time + 1
starting_time[v] = current_time
shuffle children[v] randomly (each permutation with equal possibility)
// children[v] is vector of children cities of city v
for u in children[v]:
dfs(u)
As told before, Barney will start his journey in the root of the tree (equivalent to call dfs(1)).
Now Barney needs to pack a backpack and so he wants to know more about his upcoming journey: for every city i, Barney wants to know the expected value of starting_time[i]. He's a friend of Jon Snow and knows nothing, that's why he asked for your help.
Input
The first line of input contains a single integer n (1 ≤ n ≤ 105) — the number of cities in USC.
The second line contains n - 1 integers p2, p3, ..., pn (1 ≤ pi < i), where pi is the number of the parent city of city number i in the tree, meaning there is a road between cities numbered pi and i in USC.
Output
In the first and only line of output print n numbers, where i-th number is the expected value of starting_time[i].
Your answer for each city will be considered correct if its absolute or relative error does not exceed 10 - 6.
Examples
Input
7
1 2 1 1 4 4
Output
1.0 4.0 5.0 3.5 4.5 5.0 5.0
Input
12
1 1 2 2 4 4 3 3 1 10 8
Output
1.0 5.0 5.5 6.5 7.5 8.0 8.0 7.0 7.5 6.5 7.5 8.0 | instruction | 0 | 84,662 | 1 | 169,324 |
Tags: dfs and similar, math, probabilities, trees
Correct Solution:
```
import sys
input = sys.stdin.readline
n = int(input())
par = [-1] + [int(i) - 1 for i in input().split()]
child = [[] for i in range(n)]
for i in range(1, n):
child[par[i]].append(i)
size = [1] * n
def dfs():
stack = [0]
visit = [False] * n
while stack:
u = stack[-1]
if not visit[u]:
for v in child[u]:
stack.append(v)
visit[u] = True
else:
for v in child[u]:
size[u] += size[v]
stack.pop()
ans = [0] * n
ans[0] = 1
def dfs2():
stack = [0]
while stack:
u = stack.pop()
sm = 0
for v in child[u]:
sm += size[v]
for v in child[u]:
ans[v] = (sm - size[v]) * 0.5 + 1 + ans[u]
stack.append(v)
dfs()
dfs2()
print(*ans)
``` | output | 1 | 84,662 | 1 | 169,325 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
You have got a new job, and it's very interesting, you are a ship captain. Your first task is to move your ship from one point to another point, and for sure you want to move it at the minimum cost.
And it's well known that the shortest distance between any 2 points is the length of the line segment between these 2 points. But unfortunately there is an island in the sea, so sometimes you won't be able to move your ship in the line segment between the 2 points.
You can only move to safe points. A point is called safe if it's on the line segment between the start and end points, or if it's on the island's edge.
But you are too lucky, you have got some clever and strong workers and they can help you in your trip, they can help you move the ship in the sea and they will take 1 Egyptian pound for each moving unit in the sea, and they can carry the ship (yes, they are very strong) and walk on the island and they will take 2 Egyptian pounds for each moving unit in the island. The money which you will give to them will be divided between all workers, so the number of workers does not matter here.
You can move your ship on the island edge, and it will be considered moving in the sea.
Now you have a sea map, and you have to decide what is the minimum cost for your trip.
Your starting point is (xStart, yStart), and the end point is (xEnd, yEnd), both points will be different.
The island will be a convex polygon and there will be no more than 2 polygon points on the same line, also the starting and the end points won't be inside or on the boundary of the island. The points for the polygon will be given in the anti-clockwise order.
Input
The first line contains 4 integers, xStart, yStart, xEnd and yEnd ( - 100 ≤ xStart, yStart, xEnd, yEnd ≤ 100). The second line contains an integer n, which is the number of points in the polygon (3 ≤ n ≤ 30), followed by a line containing n pairs of integers x and y, which are the coordinates of the points ( - 100 ≤ x, y ≤ 100), the polygon points will be distinct.
Output
Print one line which contains the minimum possible cost. The absolute or relative error in the answer should not exceed 10 - 6.
Examples
Input
1 7 6 7
4
4 2 4 12 3 12 3 2
Output
6.000000000
Input
-1 0 2 0
4
0 0 1 0 1 1 0 1
Output
3.000000000
Submitted Solution:
```
import sys
from array import array # noqa: F401
from math import hypot
def input():
return sys.stdin.buffer.readline().decode('utf-8')
class Point(object):
COUNTER_CLOCKWISE = 1
CLOCKWISE = -1
ONLINE_BACK = 2
ONLINE_FRONT = -2
ON_SEGMENT = 0
def __init__(self, x: int, y: int):
self.x = x
self.y = y
def __add__(self, other: 'Point'):
return Point(self.x + other.x, self.y + other.y)
def __sub__(self, other: 'Point'):
return Point(self.x - other.x, self.y - other.y)
def __mul__(self, k):
return Point(self.x * k, self.y * k)
def __repr__(self):
return f'x = {self.x}, y = {self.y}'
def norm(self):
return self.x**2 + self.y**2
def dot(self, other: 'Point'):
return self.x * other.x + self.y * other.y
def cross(self, other: 'Point'):
return self.x * other.y - self.y * other.x
def ccw(self, p1: 'Point', p2: 'Point'):
vector_a = p1 - self
vector_b = p2 - self
prod = vector_a.cross(vector_b)
if prod > 0:
return self.COUNTER_CLOCKWISE
elif prod < 0:
return self.CLOCKWISE
elif vector_a.dot(vector_b) < 0:
return self.ONLINE_BACK
elif vector_a.norm() < vector_b.norm():
return self.ONLINE_FRONT
else:
return self.ON_SEGMENT
class Segment(object):
def __init__(self, p1: Point, p2: Point):
self.p1 = p1
self.p2 = p2
def is_intersected(self, other: 'Segment'):
return (
self.p1.ccw(self.p2, other.p1) * self.p1.ccw(self.p2, other.p2) <= 0
and other.p1.ccw(other.p2, self.p1) * other.p1.ccw(other.p2, self.p2) <= 0
)
def intersection(self, other: 'Segment'):
base = other.p2 - other.p1
d1 = abs(base.cross(self.p1 - other.p1))
d2 = abs(base.cross(self.p2 - other.p1))
t = d1 / (d1 + d2)
return self.p1 + (self.p2 - self.p1) * t
sx, sy, tx, ty = map(int, input().split())
route = Segment(Point(sx, sy), Point(tx, ty))
n = int(input())
a = list(map(int, input().split()))
points = []
for i in range(0, 2 * n, 2):
points.append(Point(a[i], a[i + 1]))
segments = []
for i in range(n):
segments.append(Segment(points[i], points[(i + 1) % n]))
eps = 1e-10
intersect = [Point(sx, sy), Point(tx, ty)]
for seg in segments:
try:
if seg.is_intersected(route):
p = seg.intersection(route)
if not any(q.x - eps < p.x < q.x + eps and q.y - eps < p.y < q.y + eps for q in points):
intersect.append(p)
except ZeroDivisionError:
pass
intersect.sort(key=lambda p: (p.x - sx)**2 + (p.y - sy) ** 2)
ans = 0
for i, (p1, p2) in enumerate(zip(intersect, intersect[1:])):
ans += hypot(p1.x - p2.x, p1.y - p2.y) * ((i & 1) + 1)
print(ans)
``` | instruction | 0 | 85,412 | 1 | 170,824 |
No | output | 1 | 85,412 | 1 | 170,825 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
You have got a new job, and it's very interesting, you are a ship captain. Your first task is to move your ship from one point to another point, and for sure you want to move it at the minimum cost.
And it's well known that the shortest distance between any 2 points is the length of the line segment between these 2 points. But unfortunately there is an island in the sea, so sometimes you won't be able to move your ship in the line segment between the 2 points.
You can only move to safe points. A point is called safe if it's on the line segment between the start and end points, or if it's on the island's edge.
But you are too lucky, you have got some clever and strong workers and they can help you in your trip, they can help you move the ship in the sea and they will take 1 Egyptian pound for each moving unit in the sea, and they can carry the ship (yes, they are very strong) and walk on the island and they will take 2 Egyptian pounds for each moving unit in the island. The money which you will give to them will be divided between all workers, so the number of workers does not matter here.
You can move your ship on the island edge, and it will be considered moving in the sea.
Now you have a sea map, and you have to decide what is the minimum cost for your trip.
Your starting point is (xStart, yStart), and the end point is (xEnd, yEnd), both points will be different.
The island will be a convex polygon and there will be no more than 2 polygon points on the same line, also the starting and the end points won't be inside or on the boundary of the island. The points for the polygon will be given in the anti-clockwise order.
Input
The first line contains 4 integers, xStart, yStart, xEnd and yEnd ( - 100 ≤ xStart, yStart, xEnd, yEnd ≤ 100). The second line contains an integer n, which is the number of points in the polygon (3 ≤ n ≤ 30), followed by a line containing n pairs of integers x and y, which are the coordinates of the points ( - 100 ≤ x, y ≤ 100), the polygon points will be distinct.
Output
Print one line which contains the minimum possible cost. The absolute or relative error in the answer should not exceed 10 - 6.
Examples
Input
1 7 6 7
4
4 2 4 12 3 12 3 2
Output
6.000000000
Input
-1 0 2 0
4
0 0 1 0 1 1 0 1
Output
3.000000000
Submitted Solution:
```
import sys
from array import array # noqa: F401
from math import hypot
def input():
return sys.stdin.buffer.readline().decode('utf-8')
class Point(object):
COUNTER_CLOCKWISE = 1
CLOCKWISE = -1
ONLINE_BACK = 2
ONLINE_FRONT = -2
ON_SEGMENT = 0
def __init__(self, x: int, y: int):
self.x = x
self.y = y
def __add__(self, other: 'Point'):
return Point(self.x + other.x, self.y + other.y)
def __sub__(self, other: 'Point'):
return Point(self.x - other.x, self.y - other.y)
def __mul__(self, k):
return Point(self.x * k, self.y * k)
def __repr__(self):
return f'x = {self.x}, y = {self.y}'
def norm(self):
return self.x**2 + self.y**2
def dot(self, other: 'Point'):
return self.x * other.x + self.y * other.y
def cross(self, other: 'Point'):
return self.x * other.y - self.y * other.x
def ccw(self, p1: 'Point', p2: 'Point'):
vector_a = p1 - self
vector_b = p2 - self
prod = vector_a.cross(vector_b)
if prod > 0:
return self.COUNTER_CLOCKWISE
elif prod < 0:
return self.CLOCKWISE
elif vector_a.dot(vector_b) < 0:
return self.ONLINE_BACK
elif vector_a.norm() < vector_b.norm():
return self.ONLINE_FRONT
else:
return self.ON_SEGMENT
class Segment(object):
def __init__(self, p1: Point, p2: Point):
self.p1 = p1
self.p2 = p2
def is_intersected(self, other: 'Segment'):
return (
self.p1.ccw(self.p2, other.p1) * self.p1.ccw(self.p2, other.p2) <= 0
and other.p1.ccw(other.p2, self.p1) * other.p1.ccw(other.p2, self.p2) <= 0
)
def intersection(self, other: 'Segment'):
base = other.p2 - other.p1
d1 = abs(base.cross(self.p1 - other.p1))
d2 = abs(base.cross(self.p2 - other.p1))
t = d1 / (d1 + d2)
return self.p1 + (self.p2 - self.p1) * t
sx, sy, tx, ty = map(int, input().split())
route = Segment(Point(sx, sy), Point(tx, ty))
n = int(input())
a = list(map(int, input().split()))
points = []
for i in range(0, 2 * n, 2):
points.append(Point(a[i], a[i + 1]))
segments = []
for i in range(n):
segments.append(Segment(points[i], points[(i + 1) % n]))
eps = 1e-8
intersect = [Point(sx, sy), Point(tx, ty)]
for seg in segments:
try:
if seg.is_intersected(route):
p = seg.intersection(route)
if not any(q.x - eps < p.x < q.x + eps and q.y - eps < p.y < q.y + eps for q in points):
intersect.append(p)
except ZeroDivisionError:
pass
intersect.sort(key=lambda p: (p.x - sx)**2 + (p.y - sy) ** 2)
ans = 0
for i, (p1, p2) in enumerate(zip(intersect, intersect[1:])):
ans += hypot(p1.x - p2.x, p1.y - p2.y) * ((i & 1) + 1)
print(ans)
``` | instruction | 0 | 85,413 | 1 | 170,826 |
No | output | 1 | 85,413 | 1 | 170,827 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
A few years ago Sajjad left his school and register to another one due to security reasons. Now he wishes to find Amir, one of his schoolmates and good friends.
There are n schools numerated from 1 to n. One can travel between each pair of them, to do so, he needs to buy a ticket. The ticker between schools i and j costs <image> and can be used multiple times. Help Sajjad to find the minimum cost he needs to pay for tickets to visit all schools. He can start and finish in any school.
Input
The first line contains a single integer n (1 ≤ n ≤ 105) — the number of schools.
Output
Print single integer: the minimum cost of tickets needed to visit all schools.
Examples
Input
2
Output
0
Input
10
Output
4
Note
In the first example we can buy a ticket between the schools that costs <image>.
Submitted Solution:
```
#Winners never quit, Quitters never win............................................................................
from collections import deque as de
import math
from collections import Counter as cnt
from functools import reduce
from typing import MutableMapping
from itertools import groupby as gb
from fractions import Fraction as fr
def factors(n):
return set(reduce(list.__add__,
([i, n//i] for i in range(1, int(n**0.5) + 1) if n % i == 0)))
class My_stack():
def __init__(self):
self.data = []
def my_push(self, x):
return (self.data.append(x))
def my_pop(self):
return (self.data.pop())
def my_peak(self):
return (self.data[-1])
def my_contains(self, x):
return (self.data.count(x))
def my_show_all(self):
return (self.data)
def isEmpty(self):
return len(self.data)==0
arrStack = My_stack()
def decimalToBinary(n):
return bin(n).replace("0b", "")
def isPrime(n) :
if (n <= 1) :
return False
if (n <= 3) :
return True
if (n % 2 == 0 or n % 3 == 0) :
return False
i = 5
while(i * i <= n) :
if (n % i == 0 or n % (i + 2) == 0) :
return False
i = i + 6
return True
def get_prime_factors(number):
prime_factors = []
while number % 2 == 0:
prime_factors.append(2)
number = number / 2
for i in range(3, int(math.sqrt(number)) + 1, 2):
while number % i == 0:
prime_factors.append(int(i))
number = number / i
if number > 2:
prime_factors.append(int(number))
return prime_factors
def get_frequency(list):
dic={}
for ele in list:
if ele in dic:
dic[ele] += 1
else:
dic[ele] = 1
return dic
def Log2(x):
return (math.log10(x) /
math.log10(2));
def isPowerOfTwo(n):
return (math.ceil(Log2(n)) == math.floor(Log2(n)));
def ceildiv(x,y): return (x+y-1)//y #ceil function gives wrong answer after 10^17 so i have to create my own :)
# because i don't want to doubt on my solution of 900-1000 problem set.
def di():
return map(int, input().split())
def li():
return list(map(int, input().split()))
#here we go......................
#Winners never quit, Quitters never win
n=int(input())
if n %2:
print(n//2)
else:
print((n//2)-1)
``` | instruction | 0 | 85,433 | 1 | 170,866 |
Yes | output | 1 | 85,433 | 1 | 170,867 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
A few years ago Sajjad left his school and register to another one due to security reasons. Now he wishes to find Amir, one of his schoolmates and good friends.
There are n schools numerated from 1 to n. One can travel between each pair of them, to do so, he needs to buy a ticket. The ticker between schools i and j costs <image> and can be used multiple times. Help Sajjad to find the minimum cost he needs to pay for tickets to visit all schools. He can start and finish in any school.
Input
The first line contains a single integer n (1 ≤ n ≤ 105) — the number of schools.
Output
Print single integer: the minimum cost of tickets needed to visit all schools.
Examples
Input
2
Output
0
Input
10
Output
4
Note
In the first example we can buy a ticket between the schools that costs <image>.
Submitted Solution:
```
n = int(input())
if n% 2 == 0:
print(str(int(n/2 - 1)))
exit()
print(str(int(n//2)))
``` | instruction | 0 | 85,434 | 1 | 170,868 |
Yes | output | 1 | 85,434 | 1 | 170,869 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
A few years ago Sajjad left his school and register to another one due to security reasons. Now he wishes to find Amir, one of his schoolmates and good friends.
There are n schools numerated from 1 to n. One can travel between each pair of them, to do so, he needs to buy a ticket. The ticker between schools i and j costs <image> and can be used multiple times. Help Sajjad to find the minimum cost he needs to pay for tickets to visit all schools. He can start and finish in any school.
Input
The first line contains a single integer n (1 ≤ n ≤ 105) — the number of schools.
Output
Print single integer: the minimum cost of tickets needed to visit all schools.
Examples
Input
2
Output
0
Input
10
Output
4
Note
In the first example we can buy a ticket between the schools that costs <image>.
Submitted Solution:
```
n = int(input())
x = n//2 - 1
if n%2==0:
print(x)
else:
print(x + 1)
``` | instruction | 0 | 85,435 | 1 | 170,870 |
Yes | output | 1 | 85,435 | 1 | 170,871 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
A few years ago Sajjad left his school and register to another one due to security reasons. Now he wishes to find Amir, one of his schoolmates and good friends.
There are n schools numerated from 1 to n. One can travel between each pair of them, to do so, he needs to buy a ticket. The ticker between schools i and j costs <image> and can be used multiple times. Help Sajjad to find the minimum cost he needs to pay for tickets to visit all schools. He can start and finish in any school.
Input
The first line contains a single integer n (1 ≤ n ≤ 105) — the number of schools.
Output
Print single integer: the minimum cost of tickets needed to visit all schools.
Examples
Input
2
Output
0
Input
10
Output
4
Note
In the first example we can buy a ticket between the schools that costs <image>.
Submitted Solution:
```
def find(n):
return (n + 1) // 2 - 1
print(find(int(input())))
``` | instruction | 0 | 85,436 | 1 | 170,872 |
Yes | output | 1 | 85,436 | 1 | 170,873 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
A few years ago Sajjad left his school and register to another one due to security reasons. Now he wishes to find Amir, one of his schoolmates and good friends.
There are n schools numerated from 1 to n. One can travel between each pair of them, to do so, he needs to buy a ticket. The ticker between schools i and j costs <image> and can be used multiple times. Help Sajjad to find the minimum cost he needs to pay for tickets to visit all schools. He can start and finish in any school.
Input
The first line contains a single integer n (1 ≤ n ≤ 105) — the number of schools.
Output
Print single integer: the minimum cost of tickets needed to visit all schools.
Examples
Input
2
Output
0
Input
10
Output
4
Note
In the first example we can buy a ticket between the schools that costs <image>.
Submitted Solution:
```
s = input()
length = len(s)
miss = 0
for i in range(0, length//2):
if s[i] != s[length-1-i]:
miss += 1
if miss == 1 or (miss == 0 and length % 2 != 0):
print('YES')
else:
print('NO')
``` | instruction | 0 | 85,437 | 1 | 170,874 |
No | output | 1 | 85,437 | 1 | 170,875 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
A few years ago Sajjad left his school and register to another one due to security reasons. Now he wishes to find Amir, one of his schoolmates and good friends.
There are n schools numerated from 1 to n. One can travel between each pair of them, to do so, he needs to buy a ticket. The ticker between schools i and j costs <image> and can be used multiple times. Help Sajjad to find the minimum cost he needs to pay for tickets to visit all schools. He can start and finish in any school.
Input
The first line contains a single integer n (1 ≤ n ≤ 105) — the number of schools.
Output
Print single integer: the minimum cost of tickets needed to visit all schools.
Examples
Input
2
Output
0
Input
10
Output
4
Note
In the first example we can buy a ticket between the schools that costs <image>.
Submitted Solution:
```
print((int(input())+1)//2)
``` | instruction | 0 | 85,438 | 1 | 170,876 |
No | output | 1 | 85,438 | 1 | 170,877 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
A few years ago Sajjad left his school and register to another one due to security reasons. Now he wishes to find Amir, one of his schoolmates and good friends.
There are n schools numerated from 1 to n. One can travel between each pair of them, to do so, he needs to buy a ticket. The ticker between schools i and j costs <image> and can be used multiple times. Help Sajjad to find the minimum cost he needs to pay for tickets to visit all schools. He can start and finish in any school.
Input
The first line contains a single integer n (1 ≤ n ≤ 105) — the number of schools.
Output
Print single integer: the minimum cost of tickets needed to visit all schools.
Examples
Input
2
Output
0
Input
10
Output
4
Note
In the first example we can buy a ticket between the schools that costs <image>.
Submitted Solution:
```
I =lambda:int(input())
M =lambda:map(int,input().split())
LI=lambda:list(map(int,input().split()))
n=I()
print((n//2)-1)
``` | instruction | 0 | 85,439 | 1 | 170,878 |
No | output | 1 | 85,439 | 1 | 170,879 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
A few years ago Sajjad left his school and register to another one due to security reasons. Now he wishes to find Amir, one of his schoolmates and good friends.
There are n schools numerated from 1 to n. One can travel between each pair of them, to do so, he needs to buy a ticket. The ticker between schools i and j costs <image> and can be used multiple times. Help Sajjad to find the minimum cost he needs to pay for tickets to visit all schools. He can start and finish in any school.
Input
The first line contains a single integer n (1 ≤ n ≤ 105) — the number of schools.
Output
Print single integer: the minimum cost of tickets needed to visit all schools.
Examples
Input
2
Output
0
Input
10
Output
4
Note
In the first example we can buy a ticket between the schools that costs <image>.
Submitted Solution:
```
n = int(input())
print(max(0, n/2-1))
``` | instruction | 0 | 85,440 | 1 | 170,880 |
No | output | 1 | 85,440 | 1 | 170,881 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Joisino is planning on touring Takahashi Town. The town is divided into square sections by north-south and east-west lines. We will refer to the section that is the x-th from the west and the y-th from the north as (x,y).
Joisino thinks that a touring plan is good if it satisfies the following conditions:
* Let (p,q) be the section where she starts the tour. Then, X_1 \leq p \leq X_2 and Y_1 \leq q \leq Y_2 hold.
* Let (s,t) be the section where she has lunch. Then, X_3 \leq s \leq X_4 and Y_3 \leq t \leq Y_4 hold.
* Let (u,v) be the section where she ends the tour. Then, X_5 \leq u \leq X_6 and Y_5 \leq v \leq Y_6 hold.
* By repeatedly moving to the adjacent section (sharing a side), she travels from the starting section to the ending section in the shortest distance, passing the lunch section on the way.
Two touring plans are considered different if at least one of the following is different: the starting section, the lunch section, the ending section, and the sections that are visited on the way. Joisino would like to know how many different good touring plans there are. Find the number of the different good touring plans. Since it may be extremely large, find the count modulo 10^9+7.
Constraints
* 1 \leq X_1 \leq X_2 < X_3 \leq X_4 < X_5 \leq X_6 \leq 10^6
* 1 \leq Y_1 \leq Y_2 < Y_3 \leq Y_4 < Y_5 \leq Y_6 \leq 10^6
Input
Input is given from Standard Input in the following format:
X_1 X_2 X_3 X_4 X_5 X_6
Y_1 Y_2 Y_3 Y_4 Y_5 Y_6
Output
Print the number of the different good touring plans, modulo 10^9+7.
Examples
Input
1 1 2 2 3 4
1 1 2 2 3 3
Output
10
Input
1 2 3 4 5 6
1 2 3 4 5 6
Output
2346
Input
77523 89555 420588 604360 845669 973451
2743 188053 544330 647651 709337 988194
Output
137477680
Submitted Solution:
```
import sys
read = sys.stdin.buffer.read
readline = sys.stdin.buffer.readline
readlines = sys.stdin.buffer.readlines
import itertools
import numpy as np
from functools import lru_cache
X = list(map(int,readline().split()))
Y = list(map(int,readline().split()))
for i in [1,3,5]:
X[i] += 1
Y[i] += 1
X1 = X[:2]; X2 = X[2:4]; X3 = X[4:]
Y1 = Y[:2]; Y2 = Y[2:4]; Y3 = Y[4:]
def cumprod(arr,MOD):
L = len(arr); Lsq = int(L**.5+1)
arr = np.resize(arr,Lsq**2).reshape(Lsq,Lsq)
for n in range(1,Lsq):
arr[:,n] *= arr[:,n-1]; arr[:,n] %= MOD
for n in range(1,Lsq):
arr[n] *= arr[n-1,-1]; arr[n] %= MOD
return arr.ravel()[:L]
def make_fact(U,MOD):
x = np.arange(U,dtype=np.int64); x[0] = 1
fact = cumprod(x,MOD)
x = np.arange(U,0,-1,dtype=np.int64); x[0] = pow(int(fact[-1]),MOD-2,MOD)
fact_inv = cumprod(x,MOD)[::-1]
return fact,fact_inv
U = 2 * 10 ** 6 + 10
MOD = 10**9 + 7
fact, fact_inv = make_fact(U,MOD)
@lru_cache()
def make_comb(n):
return fact[n] * fact_inv[:n+1] % MOD * fact_inv[:n+1][::-1] % MOD
answer = 0
for p in itertools.product([0,1],repeat=6):
x1,x2,x3,y1,y2,y3 = [A[i] for A,i in zip([X1,X2,X3,Y1,Y2,Y3],p)]
sgn = (-1) ** sum(p)
a,b,c,d = x2-x1, x3-x2, x2-x1+y2-y1, x3-x2+y3-y2
c += 2; d += 2; sgn = -sgn
make_comb(c)
make_comb(d)
``` | instruction | 0 | 85,611 | 1 | 171,222 |
No | output | 1 | 85,611 | 1 | 171,223 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Joisino is planning on touring Takahashi Town. The town is divided into square sections by north-south and east-west lines. We will refer to the section that is the x-th from the west and the y-th from the north as (x,y).
Joisino thinks that a touring plan is good if it satisfies the following conditions:
* Let (p,q) be the section where she starts the tour. Then, X_1 \leq p \leq X_2 and Y_1 \leq q \leq Y_2 hold.
* Let (s,t) be the section where she has lunch. Then, X_3 \leq s \leq X_4 and Y_3 \leq t \leq Y_4 hold.
* Let (u,v) be the section where she ends the tour. Then, X_5 \leq u \leq X_6 and Y_5 \leq v \leq Y_6 hold.
* By repeatedly moving to the adjacent section (sharing a side), she travels from the starting section to the ending section in the shortest distance, passing the lunch section on the way.
Two touring plans are considered different if at least one of the following is different: the starting section, the lunch section, the ending section, and the sections that are visited on the way. Joisino would like to know how many different good touring plans there are. Find the number of the different good touring plans. Since it may be extremely large, find the count modulo 10^9+7.
Constraints
* 1 \leq X_1 \leq X_2 < X_3 \leq X_4 < X_5 \leq X_6 \leq 10^6
* 1 \leq Y_1 \leq Y_2 < Y_3 \leq Y_4 < Y_5 \leq Y_6 \leq 10^6
Input
Input is given from Standard Input in the following format:
X_1 X_2 X_3 X_4 X_5 X_6
Y_1 Y_2 Y_3 Y_4 Y_5 Y_6
Output
Print the number of the different good touring plans, modulo 10^9+7.
Examples
Input
1 1 2 2 3 4
1 1 2 2 3 3
Output
10
Input
1 2 3 4 5 6
1 2 3 4 5 6
Output
2346
Input
77523 89555 420588 604360 845669 973451
2743 188053 544330 647651 709337 988194
Output
137477680
Submitted Solution:
```
def cmb(n, r, mod):
if ( r<0 or r>n ):
return 0
r = min(r, n-r)
return g1[n] * g2[r] * g2[n-r] % mod
mod = 10**9+7 #出力の制限
N = 2*(10**6)
g1 = [1, 1] # 元テーブル
g2 = [1, 1] #逆元テーブル
inverse = [0, 1] #逆元テーブル計算用テーブル
for i in range( 2, N + 1 ):
g1.append( ( g1[-1] * i ) % mod )
inverse.append( ( -inverse[mod % i] * (mod//i) ) % mod )
g2.append( (g2[-1] * inverse[-1]) % mod )
def sihenkei(a,b,c,d):#a to c b to d
return (cmb(c+d+2,c+1,mod)-cmb(d+1+a,a,mod)-cmb(b+c+1,c+1,mod)+cmb(a+b,a,mod))%mod
x1,x2,x3,x4,x5,x6=map(int,input().split())
y1,y2,y3,y4,y5,y6=map(int,input().split())
ans=0
for i in range(x3,x4+1):
for j in range(y3,y4+1):
ans+=sihenkei(i-x2,j-y2,i-x1,j-y1)*sihenkei(x5-i,y5-j,x6-i,y6-j)
ans%=mod
print(ans)
``` | instruction | 0 | 85,612 | 1 | 171,224 |
No | output | 1 | 85,612 | 1 | 171,225 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Joisino is planning on touring Takahashi Town. The town is divided into square sections by north-south and east-west lines. We will refer to the section that is the x-th from the west and the y-th from the north as (x,y).
Joisino thinks that a touring plan is good if it satisfies the following conditions:
* Let (p,q) be the section where she starts the tour. Then, X_1 \leq p \leq X_2 and Y_1 \leq q \leq Y_2 hold.
* Let (s,t) be the section where she has lunch. Then, X_3 \leq s \leq X_4 and Y_3 \leq t \leq Y_4 hold.
* Let (u,v) be the section where she ends the tour. Then, X_5 \leq u \leq X_6 and Y_5 \leq v \leq Y_6 hold.
* By repeatedly moving to the adjacent section (sharing a side), she travels from the starting section to the ending section in the shortest distance, passing the lunch section on the way.
Two touring plans are considered different if at least one of the following is different: the starting section, the lunch section, the ending section, and the sections that are visited on the way. Joisino would like to know how many different good touring plans there are. Find the number of the different good touring plans. Since it may be extremely large, find the count modulo 10^9+7.
Constraints
* 1 \leq X_1 \leq X_2 < X_3 \leq X_4 < X_5 \leq X_6 \leq 10^6
* 1 \leq Y_1 \leq Y_2 < Y_3 \leq Y_4 < Y_5 \leq Y_6 \leq 10^6
Input
Input is given from Standard Input in the following format:
X_1 X_2 X_3 X_4 X_5 X_6
Y_1 Y_2 Y_3 Y_4 Y_5 Y_6
Output
Print the number of the different good touring plans, modulo 10^9+7.
Examples
Input
1 1 2 2 3 4
1 1 2 2 3 3
Output
10
Input
1 2 3 4 5 6
1 2 3 4 5 6
Output
2346
Input
77523 89555 420588 604360 845669 973451
2743 188053 544330 647651 709337 988194
Output
137477680
Submitted Solution:
```
import sys
read = sys.stdin.buffer.read
readline = sys.stdin.buffer.readline
readlines = sys.stdin.buffer.readlines
import itertools
import numpy as np
from functools import lru_cache
from operator import itemgetter
X = list(map(int,readline().split()))
Y = list(map(int,readline().split()))
for i in [1,3,5]:
X[i] += 1
Y[i] += 1
X1 = X[:2]; X2 = X[2:4]; X3 = X[4:]
Y1 = Y[:2]; Y2 = Y[2:4]; Y3 = Y[4:]
def cumprod(arr,MOD):
L = len(arr); Lsq = int(L**.5+1)
arr = np.resize(arr,Lsq**2).reshape(Lsq,Lsq)
for n in range(1,Lsq):
arr[:,n] *= arr[:,n-1]; arr[:,n] %= MOD
for n in range(1,Lsq):
arr[n] *= arr[n-1,-1]; arr[n] %= MOD
return arr.ravel()[:L]
def make_fact(U,MOD):
x = np.arange(U,dtype=np.int64); x[0] = 1
fact = cumprod(x,MOD)
x = np.arange(U,0,-1,dtype=np.int64); x[0] = pow(int(fact[-1]),MOD-2,MOD)
fact_inv = cumprod(x,MOD)[::-1]
return fact,fact_inv
U = 2 * 10 ** 6 + 10
MOD = 10**9 + 7
fact, fact_inv = make_fact(U,MOD)
@lru_cache(16)
def make_comb(n):
return fact[n] * fact_inv[:n+1] % MOD * fact_inv[:n+1][::-1] % MOD
answer = 0
tasks = []
for p in itertools.product([0,1],repeat=6):
x1,x2,x3,y1,y2,y3 = [A[i] for A,i in zip([X1,X2,X3,Y1,Y2,Y3],p)]
sgn = (-1) ** sum(p)
a,b,c,d = x2-x1, x3-x2, x2-x1+y2-y1, x3-x2+y3-y2
c += 2; d += 2; sgn = -sgn
tasks.append((a,b,c,d,sgn))
tasks.sort(key = itemgetter(2))
for a,b,c,d,sgn in tasks:
# (1+A)^c(1+B)^d / (A-B)^2 における A^aB^b の係数
# まずはa+b+2次式部分を抽出する:A側の次数で持つ
D = a + b + 2
# A^i B^j の寄与。
L = max(0, D-d)
R = min(c, D)
if L > R:
continue
x = make_comb(c)[L:R+1]
L,R = D-R,D-L
y = make_comb(d)[L:R+1]
x = x * y[::-1] % MOD
# B=1と見立てる。(1-A)^2 で割って、A^(a-L)の係数
np.cumsum(x,out=x)
x %= MOD
np.cumsum(x,out=x)
x %= MOD
L,R = D-R,D-L
if 0 <= a-L < len(x):
answer += sgn * x[a-L]
answer %= MOD
print(answer)
``` | instruction | 0 | 85,613 | 1 | 171,226 |
No | output | 1 | 85,613 | 1 | 171,227 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Joisino is planning on touring Takahashi Town. The town is divided into square sections by north-south and east-west lines. We will refer to the section that is the x-th from the west and the y-th from the north as (x,y).
Joisino thinks that a touring plan is good if it satisfies the following conditions:
* Let (p,q) be the section where she starts the tour. Then, X_1 \leq p \leq X_2 and Y_1 \leq q \leq Y_2 hold.
* Let (s,t) be the section where she has lunch. Then, X_3 \leq s \leq X_4 and Y_3 \leq t \leq Y_4 hold.
* Let (u,v) be the section where she ends the tour. Then, X_5 \leq u \leq X_6 and Y_5 \leq v \leq Y_6 hold.
* By repeatedly moving to the adjacent section (sharing a side), she travels from the starting section to the ending section in the shortest distance, passing the lunch section on the way.
Two touring plans are considered different if at least one of the following is different: the starting section, the lunch section, the ending section, and the sections that are visited on the way. Joisino would like to know how many different good touring plans there are. Find the number of the different good touring plans. Since it may be extremely large, find the count modulo 10^9+7.
Constraints
* 1 \leq X_1 \leq X_2 < X_3 \leq X_4 < X_5 \leq X_6 \leq 10^6
* 1 \leq Y_1 \leq Y_2 < Y_3 \leq Y_4 < Y_5 \leq Y_6 \leq 10^6
Input
Input is given from Standard Input in the following format:
X_1 X_2 X_3 X_4 X_5 X_6
Y_1 Y_2 Y_3 Y_4 Y_5 Y_6
Output
Print the number of the different good touring plans, modulo 10^9+7.
Examples
Input
1 1 2 2 3 4
1 1 2 2 3 3
Output
10
Input
1 2 3 4 5 6
1 2 3 4 5 6
Output
2346
Input
77523 89555 420588 604360 845669 973451
2743 188053 544330 647651 709337 988194
Output
137477680
Submitted Solution:
```
import sys
read = sys.stdin.buffer.read
readline = sys.stdin.buffer.readline
readlines = sys.stdin.buffer.readlines
N,M,*X = map(int,read().split())
MOD = 10 ** 9 + 7
def mult(a,b,c,d,e,f):
# (a+bx+cx^2)(d+ex+fx^2) modulo 1-4x+2x^2-x^3
a,b,c,d,e = a*d,a*e+b*d,a*f+b*e+c*d,b*f+c*e,c*f
b += e; c -= 4*e; d += 2*e; e = 0
a += d; b -= 4*d; c += 2*d; d = 0
a %= MOD; b %= MOD; c %= MOD
return a,b,c
# (1/x)^i modulo (1-4x+2x^2-x^3)
M = 10 ** 5
A1 = [0] * (M+1)
a,b,c = 1,0,0
for i in range(M+1):
A1[i] = (a,b,c)
a,b,c = b+4*a,c-2*a,a
a %= MOD; b %= MOD; c %= MOD
# (1/x)^Mi modulo (1-4x+2x^2-x^3)
A2 = [0] * (M+1)
a,b,c = 1,0,0
d,e,f = A1[M]
for i in range(M+1):
A2[i] = (a,b,c)
a,b,c = mult(a,b,c,d,e,f)
def power(n):
# (1/x)^n modulo (1-4x+2x^2-x^3)
q,r = divmod(n,M)
a,b,c = A1[r]
d,e,f = A2[q]
return mult(a,b,c,d,e,f)
X.append(N)
a,b,c = 0,1,1
prev_x = 0
for x in X:
a,b,c = mult(a,b,c,*power(x - prev_x))
b -= a; c -= a
prev_x = x
answer = a
print(answer)
``` | instruction | 0 | 85,614 | 1 | 171,228 |
No | output | 1 | 85,614 | 1 | 171,229 |
Provide a correct Python 3 solution for this coding contest problem.
Taro is planning a long trip by train during the summer vacation. However, in order for Taro, who is a high school student, to travel as far as possible during the summer vacation, which has only one month, he cannot make a good plan unless he finds the cheapest and the fastest way. Let's create a program to help Taro's plan so that he can enjoy a wonderful trip.
<image>
Create a program that outputs the minimum amount or the shortest time in response to inquiries by inputting track information and the number of stations.
Input
A sequence of multiple datasets is given as input. The end of the input is indicated by two lines of zeros. Each dataset is given in the following format:
n m
a1 b1 cost1 time1
a2 b2 cost2 time2
::
an bn costn timen
k
p1 q1 r1
p2 q2 r2
::
pk qk rk
The first line gives the number of track information n (1 ≤ n ≤ 3000) and the number of stations m (1 ≤ m ≤ 100).
The following n lines give information on the i-th line. As information on each line, the numbers ai, bi (1 ≤ ai, bi ≤ m) of the two stations connecting the lines, the toll costi (1 ≤ costi ≤ 1000), and the travel time timei (1 ≤ timei ≤ 1000) are given. I will. However, each station shall be numbered in order from 1 to m. If ai and bi are connected by railroad tracks, both ai to bi and bi to ai can be moved at the same rate and time.
The following line is given the number of queries k (1 ≤ k ≤ 200). The next k line is given the i-th query. For each query, the departure station pi, the arrival station qi, and the type of value to output ri (0 or 1) are given. Inquiries must have a route.
The number of datasets does not exceed 50.
Output
Outputs the minimum amount or minimum time on one line for each data set. When ri is 0, the minimum amount is output, and when ri is 1, the minimum time is output.
Example
Input
6 5
1 2 200 10
1 4 400 15
1 3 250 25
2 4 100 10
4 5 150 20
3 5 300 20
2
1 5 0
1 5 1
0 0
Output
450
35 | instruction | 0 | 85,636 | 1 | 171,272 |
"Correct Solution:
```
from heapq import heappop, heappush
class WeightedEdge:
"""Weighted edge."""
def __init__(self, a, b, weight):
self.a = a
self.b = b
self.weight = weight
def __repr__(self):
return "(%d - %d: %d)" % (self.a, self.b, self.weight)
def __lt__(self, other):
return self.a < other.b
class EdgeWeightedGraph:
"""Undirected Edge-weighted graph (1-n indexed)."""
def __init__(self, V):
self.__adj = [[] for _ in range(V + 1)]
def add_edge(self, a, b, weight):
self.__adj[a].append(WeightedEdge(a, b, weight))
self.__adj[b].append(WeightedEdge(b, a, weight))
def adj(self, a):
return self.__adj[a]
def num_nodes(self):
return len(self.__adj) - 1
class Dijkstra:
"""Single root shortest path by Dijkstra."""
def __init__(self, graph, s, t):
self.dist_to = [float('inf') for _ in range(graph.num_nodes() + 1)]
self.dist_to[s] = 0
pq = []
heappush(pq, (0, s))
while pq:
w, a = heappop(pq)
if a == t:
return
if self.dist_to[a] < w:
continue
for edge in graph.adj(a):
if self.dist_to[edge.b] > self.dist_to[a] + edge.weight:
self.dist_to[edge.b] = self.dist_to[a] + edge.weight
heappush(pq, (self.dist_to[edge.b], edge.b))
if __name__ == '__main__':
while True:
n, m = map(int, input().split())
if n == 0 and m == 0:
break
g_cost = EdgeWeightedGraph(m)
g_time = EdgeWeightedGraph(m)
for _ in range(n):
a, b, cost, time = map(int, input().split())
g_cost.add_edge(a, b, cost)
g_time.add_edge(a, b, time)
k = int(input())
for _ in range(k):
p, q, r = map(int, input().split())
if r == 0:
fw_cost = Dijkstra(g_cost, p, q)
ans = fw_cost.dist_to[q]
else:
fw_time = Dijkstra(g_time, p, q)
ans = fw_time.dist_to[q]
print(ans)
``` | output | 1 | 85,636 | 1 | 171,273 |
Provide a correct Python 3 solution for this coding contest problem.
Taro is planning a long trip by train during the summer vacation. However, in order for Taro, who is a high school student, to travel as far as possible during the summer vacation, which has only one month, he cannot make a good plan unless he finds the cheapest and the fastest way. Let's create a program to help Taro's plan so that he can enjoy a wonderful trip.
<image>
Create a program that outputs the minimum amount or the shortest time in response to inquiries by inputting track information and the number of stations.
Input
A sequence of multiple datasets is given as input. The end of the input is indicated by two lines of zeros. Each dataset is given in the following format:
n m
a1 b1 cost1 time1
a2 b2 cost2 time2
::
an bn costn timen
k
p1 q1 r1
p2 q2 r2
::
pk qk rk
The first line gives the number of track information n (1 ≤ n ≤ 3000) and the number of stations m (1 ≤ m ≤ 100).
The following n lines give information on the i-th line. As information on each line, the numbers ai, bi (1 ≤ ai, bi ≤ m) of the two stations connecting the lines, the toll costi (1 ≤ costi ≤ 1000), and the travel time timei (1 ≤ timei ≤ 1000) are given. I will. However, each station shall be numbered in order from 1 to m. If ai and bi are connected by railroad tracks, both ai to bi and bi to ai can be moved at the same rate and time.
The following line is given the number of queries k (1 ≤ k ≤ 200). The next k line is given the i-th query. For each query, the departure station pi, the arrival station qi, and the type of value to output ri (0 or 1) are given. Inquiries must have a route.
The number of datasets does not exceed 50.
Output
Outputs the minimum amount or minimum time on one line for each data set. When ri is 0, the minimum amount is output, and when ri is 1, the minimum time is output.
Example
Input
6 5
1 2 200 10
1 4 400 15
1 3 250 25
2 4 100 10
4 5 150 20
3 5 300 20
2
1 5 0
1 5 1
0 0
Output
450
35 | instruction | 0 | 85,637 | 1 | 171,274 |
"Correct Solution:
```
def warshall_floyd(v_count: int, matrix: list) -> list:
""" ワーシャルフロイド
:param v_count: 頂点数
:param matrix: 隣接行列(到達不能はfloat("inf"))
"""
# 到達不能をfloat("inf")にしておけば余計なチェックを入れなくても
# inf > inf+(-1) のような到達不能+負辺が繋がってしまうことはない
for i in range(v_count):
for j, c2 in enumerate(row[i] for row in matrix):
for k, (c1, c3) in enumerate(zip(matrix[j], matrix[i])):
if c1 > c2+c3:
matrix[j][k] = c2+c3
return matrix
while True:
e_count, v_count = map(int, input().split())
if not e_count:
break
inf = float("inf")
edges_cost, edges_time = [[inf]*v_count for _ in [0]*v_count], [[inf]*v_count for _ in [0]*v_count]
for _ in [0]*e_count:
a, b, cost, time = map(int, input().split())
a, b = a-1, b-1
edges_cost[a][b] = cost
edges_cost[b][a] = cost
edges_time[a][b] = time
edges_time[b][a] = time
warshall_floyd(v_count, edges_cost)
warshall_floyd(v_count, edges_time)
for _ in [0]*int(input()):
p, q, r = map(int, input().split())
print((edges_time if r else edges_cost)[p-1][q-1])
``` | output | 1 | 85,637 | 1 | 171,275 |
Provide a correct Python 3 solution for this coding contest problem.
Taro is planning a long trip by train during the summer vacation. However, in order for Taro, who is a high school student, to travel as far as possible during the summer vacation, which has only one month, he cannot make a good plan unless he finds the cheapest and the fastest way. Let's create a program to help Taro's plan so that he can enjoy a wonderful trip.
<image>
Create a program that outputs the minimum amount or the shortest time in response to inquiries by inputting track information and the number of stations.
Input
A sequence of multiple datasets is given as input. The end of the input is indicated by two lines of zeros. Each dataset is given in the following format:
n m
a1 b1 cost1 time1
a2 b2 cost2 time2
::
an bn costn timen
k
p1 q1 r1
p2 q2 r2
::
pk qk rk
The first line gives the number of track information n (1 ≤ n ≤ 3000) and the number of stations m (1 ≤ m ≤ 100).
The following n lines give information on the i-th line. As information on each line, the numbers ai, bi (1 ≤ ai, bi ≤ m) of the two stations connecting the lines, the toll costi (1 ≤ costi ≤ 1000), and the travel time timei (1 ≤ timei ≤ 1000) are given. I will. However, each station shall be numbered in order from 1 to m. If ai and bi are connected by railroad tracks, both ai to bi and bi to ai can be moved at the same rate and time.
The following line is given the number of queries k (1 ≤ k ≤ 200). The next k line is given the i-th query. For each query, the departure station pi, the arrival station qi, and the type of value to output ri (0 or 1) are given. Inquiries must have a route.
The number of datasets does not exceed 50.
Output
Outputs the minimum amount or minimum time on one line for each data set. When ri is 0, the minimum amount is output, and when ri is 1, the minimum time is output.
Example
Input
6 5
1 2 200 10
1 4 400 15
1 3 250 25
2 4 100 10
4 5 150 20
3 5 300 20
2
1 5 0
1 5 1
0 0
Output
450
35 | instruction | 0 | 85,638 | 1 | 171,276 |
"Correct Solution:
```
from heapq import heappush, heappop
def Dijkstra(graph, start, goal):
que = [(0, start)]
visited = [False] * len(graph)
while True:
path_len, v = heappop(que)
visited[v] = True
if v == goal:
print(path_len)
break
for w, edge_len in graph[v].items():
if not visited[w]:
heappush(que, (path_len + edge_len, w))
while(True):
dicco = {}
dicti = {}
n,m = map(int, input().split())
if n == 0 and m == 0:
break
for i in range(m):
dicco[i] = {}
dicti[i] = {}
for _ in range(n):
a,b,c,t = map(int, input().split())
dicco[a-1][b-1] = c
dicco[b-1][a-1] = c
dicti[a-1][b-1] = t
dicti[b-1][a-1] = t
k = int(input())
for _ in range(k):
p,q,r = map(int, input().split())
if not r:
Dijkstra(dicco, p-1, q-1)
else:
Dijkstra(dicti, p-1, q-1)
``` | output | 1 | 85,638 | 1 | 171,277 |
Provide a correct Python 3 solution for this coding contest problem.
Taro is planning a long trip by train during the summer vacation. However, in order for Taro, who is a high school student, to travel as far as possible during the summer vacation, which has only one month, he cannot make a good plan unless he finds the cheapest and the fastest way. Let's create a program to help Taro's plan so that he can enjoy a wonderful trip.
<image>
Create a program that outputs the minimum amount or the shortest time in response to inquiries by inputting track information and the number of stations.
Input
A sequence of multiple datasets is given as input. The end of the input is indicated by two lines of zeros. Each dataset is given in the following format:
n m
a1 b1 cost1 time1
a2 b2 cost2 time2
::
an bn costn timen
k
p1 q1 r1
p2 q2 r2
::
pk qk rk
The first line gives the number of track information n (1 ≤ n ≤ 3000) and the number of stations m (1 ≤ m ≤ 100).
The following n lines give information on the i-th line. As information on each line, the numbers ai, bi (1 ≤ ai, bi ≤ m) of the two stations connecting the lines, the toll costi (1 ≤ costi ≤ 1000), and the travel time timei (1 ≤ timei ≤ 1000) are given. I will. However, each station shall be numbered in order from 1 to m. If ai and bi are connected by railroad tracks, both ai to bi and bi to ai can be moved at the same rate and time.
The following line is given the number of queries k (1 ≤ k ≤ 200). The next k line is given the i-th query. For each query, the departure station pi, the arrival station qi, and the type of value to output ri (0 or 1) are given. Inquiries must have a route.
The number of datasets does not exceed 50.
Output
Outputs the minimum amount or minimum time on one line for each data set. When ri is 0, the minimum amount is output, and when ri is 1, the minimum time is output.
Example
Input
6 5
1 2 200 10
1 4 400 15
1 3 250 25
2 4 100 10
4 5 150 20
3 5 300 20
2
1 5 0
1 5 1
0 0
Output
450
35 | instruction | 0 | 85,639 | 1 | 171,278 |
"Correct Solution:
```
from heapq import heappop as hpop
from heapq import heappush as hpush
def main():
while True:
n, m = map(int, input().split())
if not n:
break
cost_edges = [[] for _ in range(m)]
time_edges = [[] for _ in range(m)]
for _ in range(n):
a, b, c, t = map(int, input().split())
cost_edges[a - 1].append((c, b - 1))
cost_edges[b - 1].append((c, a - 1))
time_edges[a - 1].append((t, b - 1))
time_edges[b - 1].append((t, a - 1))
k = int(input())
for _ in range(k):
start, goal, r = map(int ,input().split())
start -= 1
goal -= 1
if r:
edges = time_edges
else:
edges = cost_edges
que = [(0, start)]
visited = [False for _ in range(m)]
while True:
score, station = hpop(que)
visited[station] = True
if station == goal:
print(score)
break
for c, to_station in edges[station]:
if not visited[to_station]:
hpush(que, (score + c, to_station))
main()
``` | output | 1 | 85,639 | 1 | 171,279 |
Provide a correct Python 3 solution for this coding contest problem.
Taro is planning a long trip by train during the summer vacation. However, in order for Taro, who is a high school student, to travel as far as possible during the summer vacation, which has only one month, he cannot make a good plan unless he finds the cheapest and the fastest way. Let's create a program to help Taro's plan so that he can enjoy a wonderful trip.
<image>
Create a program that outputs the minimum amount or the shortest time in response to inquiries by inputting track information and the number of stations.
Input
A sequence of multiple datasets is given as input. The end of the input is indicated by two lines of zeros. Each dataset is given in the following format:
n m
a1 b1 cost1 time1
a2 b2 cost2 time2
::
an bn costn timen
k
p1 q1 r1
p2 q2 r2
::
pk qk rk
The first line gives the number of track information n (1 ≤ n ≤ 3000) and the number of stations m (1 ≤ m ≤ 100).
The following n lines give information on the i-th line. As information on each line, the numbers ai, bi (1 ≤ ai, bi ≤ m) of the two stations connecting the lines, the toll costi (1 ≤ costi ≤ 1000), and the travel time timei (1 ≤ timei ≤ 1000) are given. I will. However, each station shall be numbered in order from 1 to m. If ai and bi are connected by railroad tracks, both ai to bi and bi to ai can be moved at the same rate and time.
The following line is given the number of queries k (1 ≤ k ≤ 200). The next k line is given the i-th query. For each query, the departure station pi, the arrival station qi, and the type of value to output ri (0 or 1) are given. Inquiries must have a route.
The number of datasets does not exceed 50.
Output
Outputs the minimum amount or minimum time on one line for each data set. When ri is 0, the minimum amount is output, and when ri is 1, the minimum time is output.
Example
Input
6 5
1 2 200 10
1 4 400 15
1 3 250 25
2 4 100 10
4 5 150 20
3 5 300 20
2
1 5 0
1 5 1
0 0
Output
450
35 | instruction | 0 | 85,640 | 1 | 171,280 |
"Correct Solution:
```
import heapq
import sys
from collections import defaultdict
def dijkstra(graph, size, start):
d = [float('inf')] * size
d[start] = 0
q = [(0, start)]
while len(q):
du, u = heapq.heappop(q)
for length, v in graph[u]:
if d[v] > du + length:
d[v] = du + length
heapq.heappush(q, (d[v], v))
return d
f = sys.stdin
while True:
n, m = map(int, f.readline().split())
if n == 0:
break
abct = [map(int, f.readline().split()) for _ in range(n)]
d = [defaultdict(list), defaultdict(list)]
for ai, bi, ci, ti in abct:
ai -= 1
bi -= 1
d[0][ai].append((ci, bi))
d[0][bi].append((ci, ai))
d[1][ai].append((ti, bi))
d[1][bi].append((ti, ai))
dist = {}
for i in range(int(f.readline())):
p, q, r = map(int, f.readline().split())
p -= 1
q -= 1
try:
print(dist[(q,r)][p])
except KeyError:
try:
print(dist[(p,r)][q])
except:
dist[(p,r)] = dijkstra(d[r], m, p)
print(dist[(p,r)][q])
``` | output | 1 | 85,640 | 1 | 171,281 |
Provide a correct Python 3 solution for this coding contest problem.
Taro is planning a long trip by train during the summer vacation. However, in order for Taro, who is a high school student, to travel as far as possible during the summer vacation, which has only one month, he cannot make a good plan unless he finds the cheapest and the fastest way. Let's create a program to help Taro's plan so that he can enjoy a wonderful trip.
<image>
Create a program that outputs the minimum amount or the shortest time in response to inquiries by inputting track information and the number of stations.
Input
A sequence of multiple datasets is given as input. The end of the input is indicated by two lines of zeros. Each dataset is given in the following format:
n m
a1 b1 cost1 time1
a2 b2 cost2 time2
::
an bn costn timen
k
p1 q1 r1
p2 q2 r2
::
pk qk rk
The first line gives the number of track information n (1 ≤ n ≤ 3000) and the number of stations m (1 ≤ m ≤ 100).
The following n lines give information on the i-th line. As information on each line, the numbers ai, bi (1 ≤ ai, bi ≤ m) of the two stations connecting the lines, the toll costi (1 ≤ costi ≤ 1000), and the travel time timei (1 ≤ timei ≤ 1000) are given. I will. However, each station shall be numbered in order from 1 to m. If ai and bi are connected by railroad tracks, both ai to bi and bi to ai can be moved at the same rate and time.
The following line is given the number of queries k (1 ≤ k ≤ 200). The next k line is given the i-th query. For each query, the departure station pi, the arrival station qi, and the type of value to output ri (0 or 1) are given. Inquiries must have a route.
The number of datasets does not exceed 50.
Output
Outputs the minimum amount or minimum time on one line for each data set. When ri is 0, the minimum amount is output, and when ri is 1, the minimum time is output.
Example
Input
6 5
1 2 200 10
1 4 400 15
1 3 250 25
2 4 100 10
4 5 150 20
3 5 300 20
2
1 5 0
1 5 1
0 0
Output
450
35 | instruction | 0 | 85,641 | 1 | 171,282 |
"Correct Solution:
```
from heapq import heappop as hpop
from heapq import heappush as hpush
def main():
while True:
n, m = map(int, input().split())
if not n:
break
cost_edges = [[] for _ in range(m)]
time_edges = [[] for _ in range(m)]
for _ in range(n):
a, b, c, t = map(int, input().split())
cost_edges[a - 1].append((c, b - 1))
cost_edges[b - 1].append((c, a - 1))
time_edges[a - 1].append((t, b - 1))
time_edges[b - 1].append((t, a - 1))
k = int(input())
for _ in range(k):
start, goal, r = map(int ,input().split())
start -= 1
goal -= 1
if r:
edges = time_edges
else:
edges = cost_edges
que = [(0, start)]
visited = [False for _ in range(m)]
while que:
score, station = hpop(que)
visited[station] = True
if station == goal:
print(score)
break
for c, to_station in edges[station]:
if not visited[to_station]:
hpush(que, (score + c, to_station))
main()
``` | output | 1 | 85,641 | 1 | 171,283 |
Provide a correct Python 3 solution for this coding contest problem.
Taro is planning a long trip by train during the summer vacation. However, in order for Taro, who is a high school student, to travel as far as possible during the summer vacation, which has only one month, he cannot make a good plan unless he finds the cheapest and the fastest way. Let's create a program to help Taro's plan so that he can enjoy a wonderful trip.
<image>
Create a program that outputs the minimum amount or the shortest time in response to inquiries by inputting track information and the number of stations.
Input
A sequence of multiple datasets is given as input. The end of the input is indicated by two lines of zeros. Each dataset is given in the following format:
n m
a1 b1 cost1 time1
a2 b2 cost2 time2
::
an bn costn timen
k
p1 q1 r1
p2 q2 r2
::
pk qk rk
The first line gives the number of track information n (1 ≤ n ≤ 3000) and the number of stations m (1 ≤ m ≤ 100).
The following n lines give information on the i-th line. As information on each line, the numbers ai, bi (1 ≤ ai, bi ≤ m) of the two stations connecting the lines, the toll costi (1 ≤ costi ≤ 1000), and the travel time timei (1 ≤ timei ≤ 1000) are given. I will. However, each station shall be numbered in order from 1 to m. If ai and bi are connected by railroad tracks, both ai to bi and bi to ai can be moved at the same rate and time.
The following line is given the number of queries k (1 ≤ k ≤ 200). The next k line is given the i-th query. For each query, the departure station pi, the arrival station qi, and the type of value to output ri (0 or 1) are given. Inquiries must have a route.
The number of datasets does not exceed 50.
Output
Outputs the minimum amount or minimum time on one line for each data set. When ri is 0, the minimum amount is output, and when ri is 1, the minimum time is output.
Example
Input
6 5
1 2 200 10
1 4 400 15
1 3 250 25
2 4 100 10
4 5 150 20
3 5 300 20
2
1 5 0
1 5 1
0 0
Output
450
35 | instruction | 0 | 85,642 | 1 | 171,284 |
"Correct Solution:
```
from heapq import heappush, heappop
import sys
readline = sys.stdin.readline
write = sys.stdout.write
def solve():
M, N = map(int, readline().split())
if M == N == 0:
return False
G = [[] for i in range(N)]
INF = 10**18
def solve(s, t, u):
dist = [INF]*N
dist[s] = 0
que = [(0, s)]
while que:
cost, v = heappop(que)
if dist[v] < cost:
continue
for e in G[v]:
w = e[0]
if cost + e[u] < dist[w]:
dist[w] = d = cost + e[u]
heappush(que, (d, w))
return dist[t]
for i in range(M):
a, b, c, t = map(int, readline().split()); a -= 1; b -= 1
G[a].append((b, c, t))
G[b].append((a, c, t))
K = int(readline())
for i in range(K):
p, q, r = map(int, readline().split())
write("%d\n" % solve(p-1, q-1, r+1))
return True
while solve():
...
``` | output | 1 | 85,642 | 1 | 171,285 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Taro is planning a long trip by train during the summer vacation. However, in order for Taro, who is a high school student, to travel as far as possible during the summer vacation, which has only one month, he cannot make a good plan unless he finds the cheapest and the fastest way. Let's create a program to help Taro's plan so that he can enjoy a wonderful trip.
<image>
Create a program that outputs the minimum amount or the shortest time in response to inquiries by inputting track information and the number of stations.
Input
A sequence of multiple datasets is given as input. The end of the input is indicated by two lines of zeros. Each dataset is given in the following format:
n m
a1 b1 cost1 time1
a2 b2 cost2 time2
::
an bn costn timen
k
p1 q1 r1
p2 q2 r2
::
pk qk rk
The first line gives the number of track information n (1 ≤ n ≤ 3000) and the number of stations m (1 ≤ m ≤ 100).
The following n lines give information on the i-th line. As information on each line, the numbers ai, bi (1 ≤ ai, bi ≤ m) of the two stations connecting the lines, the toll costi (1 ≤ costi ≤ 1000), and the travel time timei (1 ≤ timei ≤ 1000) are given. I will. However, each station shall be numbered in order from 1 to m. If ai and bi are connected by railroad tracks, both ai to bi and bi to ai can be moved at the same rate and time.
The following line is given the number of queries k (1 ≤ k ≤ 200). The next k line is given the i-th query. For each query, the departure station pi, the arrival station qi, and the type of value to output ri (0 or 1) are given. Inquiries must have a route.
The number of datasets does not exceed 50.
Output
Outputs the minimum amount or minimum time on one line for each data set. When ri is 0, the minimum amount is output, and when ri is 1, the minimum time is output.
Example
Input
6 5
1 2 200 10
1 4 400 15
1 3 250 25
2 4 100 10
4 5 150 20
3 5 300 20
2
1 5 0
1 5 1
0 0
Output
450
35
Submitted Solution:
```
def warshall_floyd(d):
for k in range(len(d)):
for i in range(len(d)):
for j in range(len(d)):
if d[i][j] > d[i][k] + d[k][j]:
d[i][j] = d[i][k] + d[k][j]
import sys
f = sys.stdin
while True:
n, m = map(int, f.readline().split())
if n == 0:
break
abct = [list(map(int, f.readline().split())) for _ in range(n)]
d = [[[float('inf')] * m for i in range(m)], [[float('inf')] * m for i in range(m)]]
for ai, bi, ci, ti in abct:
d[0][ai - 1][bi - 1] = ci
d[1][ai - 1][bi - 1] = ti
warshall_floyd(d[0])
warshall_floyd(d[1])
for i in range(int(f.readline())):
p, q, r = map(int, f.readline().split())
print(d[r][p - 1][q - 1])
``` | instruction | 0 | 85,643 | 1 | 171,286 |
No | output | 1 | 85,643 | 1 | 171,287 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Taro is planning a long trip by train during the summer vacation. However, in order for Taro, who is a high school student, to travel as far as possible during the summer vacation, which has only one month, he cannot make a good plan unless he finds the cheapest and the fastest way. Let's create a program to help Taro's plan so that he can enjoy a wonderful trip.
<image>
Create a program that outputs the minimum amount or the shortest time in response to inquiries by inputting track information and the number of stations.
Input
A sequence of multiple datasets is given as input. The end of the input is indicated by two lines of zeros. Each dataset is given in the following format:
n m
a1 b1 cost1 time1
a2 b2 cost2 time2
::
an bn costn timen
k
p1 q1 r1
p2 q2 r2
::
pk qk rk
The first line gives the number of track information n (1 ≤ n ≤ 3000) and the number of stations m (1 ≤ m ≤ 100).
The following n lines give information on the i-th line. As information on each line, the numbers ai, bi (1 ≤ ai, bi ≤ m) of the two stations connecting the lines, the toll costi (1 ≤ costi ≤ 1000), and the travel time timei (1 ≤ timei ≤ 1000) are given. I will. However, each station shall be numbered in order from 1 to m. If ai and bi are connected by railroad tracks, both ai to bi and bi to ai can be moved at the same rate and time.
The following line is given the number of queries k (1 ≤ k ≤ 200). The next k line is given the i-th query. For each query, the departure station pi, the arrival station qi, and the type of value to output ri (0 or 1) are given. Inquiries must have a route.
The number of datasets does not exceed 50.
Output
Outputs the minimum amount or minimum time on one line for each data set. When ri is 0, the minimum amount is output, and when ri is 1, the minimum time is output.
Example
Input
6 5
1 2 200 10
1 4 400 15
1 3 250 25
2 4 100 10
4 5 150 20
3 5 300 20
2
1 5 0
1 5 1
0 0
Output
450
35
Submitted Solution:
```
# coding: utf-8
class Route:
def __init__(self, next_station, need_price, need_time):
self.next_station = next_station
self.need_price = need_price
self.need_time = need_time
class Station:
def __init__(self):
self.routes = []
def addRoute(self,route):
self.routes.append(route)
class Status:
def __init__(self, now_station, use_price, use_time):
self.now_station = now_station
self.use_price = use_price
self.use_time = use_time
def search(stations, start, end, search_type):
result = [9999999999]
queue = []
for route in stations[start].routes:
queue.append(Status(route.next_station, route.need_price, route.need_time))
while len(queue) > 0:
status = queue.pop(0)
if status.now_station == end:
r = status.use_price if search_type == 0 else status.use_time
result.append(r)
for route in stations[status.now_station].routes:
update_price = route.need_price + status.use_price
update_time = route.need_time + status.use_time
queue.append(Status(route.next_station, update_price, update_time))
print(sorted(result)[0])
route_count, station_count = map(int, input().split(" "))
stations = [Station() for station in range(station_count)]
for count in range(route_count):
now_station, next_station, need_price, need_time = map(int, input().split(" "))
stations[now_station - 1].addRoute(Route(next_station - 1, need_price, need_time))
search_count = int(input())
for count in range(search_count):
start, end, search_type = map(int, input().split(" "))
search(stations, start - 1, end - 1, search_type)
``` | instruction | 0 | 85,644 | 1 | 171,288 |
No | output | 1 | 85,644 | 1 | 171,289 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Taro is planning a long trip by train during the summer vacation. However, in order for Taro, who is a high school student, to travel as far as possible during the summer vacation, which has only one month, he cannot make a good plan unless he finds the cheapest and the fastest way. Let's create a program to help Taro's plan so that he can enjoy a wonderful trip.
<image>
Create a program that outputs the minimum amount or the shortest time in response to inquiries by inputting track information and the number of stations.
Input
A sequence of multiple datasets is given as input. The end of the input is indicated by two lines of zeros. Each dataset is given in the following format:
n m
a1 b1 cost1 time1
a2 b2 cost2 time2
::
an bn costn timen
k
p1 q1 r1
p2 q2 r2
::
pk qk rk
The first line gives the number of track information n (1 ≤ n ≤ 3000) and the number of stations m (1 ≤ m ≤ 100).
The following n lines give information on the i-th line. As information on each line, the numbers ai, bi (1 ≤ ai, bi ≤ m) of the two stations connecting the lines, the toll costi (1 ≤ costi ≤ 1000), and the travel time timei (1 ≤ timei ≤ 1000) are given. I will. However, each station shall be numbered in order from 1 to m. If ai and bi are connected by railroad tracks, both ai to bi and bi to ai can be moved at the same rate and time.
The following line is given the number of queries k (1 ≤ k ≤ 200). The next k line is given the i-th query. For each query, the departure station pi, the arrival station qi, and the type of value to output ri (0 or 1) are given. Inquiries must have a route.
The number of datasets does not exceed 50.
Output
Outputs the minimum amount or minimum time on one line for each data set. When ri is 0, the minimum amount is output, and when ri is 1, the minimum time is output.
Example
Input
6 5
1 2 200 10
1 4 400 15
1 3 250 25
2 4 100 10
4 5 150 20
3 5 300 20
2
1 5 0
1 5 1
0 0
Output
450
35
Submitted Solution:
```
# -*- coding: utf-8 -*-
"""
http://judge.u-aizu.ac.jp/onlinejudge/description.jsp?id=0200
"""
import sys
from sys import stdin
input = stdin.readline
def warshallFloyd(V, dp):
for k in range(1, V):
for i in range(1, V):
for j in range(1, V):
if dp[i][k][0] + dp[k][j][0] < dp[i][j][0]:
dp[i][j][0] = dp[i][k][0] + dp[k][j][0]
if dp[i][k][1] + dp[k][j][1] < dp[i][j][1]:
dp[i][j][1] = dp[i][k][1] + dp[k][j][1]
def main(args):
while True:
n, m = map(int, input().split())
if n == 0 and m == 0:
break
dp = [[[float('inf'), float('inf')]] * (m+1) for _ in range(m+1)]
for i in range(m+1):
dp[i][i] = [0, 0]
for _ in range(n):
a, b, cost, time = map(int, input().split())
dp[a][b] = [time, cost]
dp[b][a] = [time, cost]
warshallFloyd(m+1, dp)
k = int(input())
for _ in range(k):
p, q, r = map(int, input().split())
if r == 0: # cost
print(dp[p][q][1])
else: # time
print(dp[p][q][0])
if __name__ == '__main__':
main(sys.argv[1:])
``` | instruction | 0 | 85,645 | 1 | 171,290 |
No | output | 1 | 85,645 | 1 | 171,291 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Taro is planning a long trip by train during the summer vacation. However, in order for Taro, who is a high school student, to travel as far as possible during the summer vacation, which has only one month, he cannot make a good plan unless he finds the cheapest and the fastest way. Let's create a program to help Taro's plan so that he can enjoy a wonderful trip.
<image>
Create a program that outputs the minimum amount or the shortest time in response to inquiries by inputting track information and the number of stations.
Input
A sequence of multiple datasets is given as input. The end of the input is indicated by two lines of zeros. Each dataset is given in the following format:
n m
a1 b1 cost1 time1
a2 b2 cost2 time2
::
an bn costn timen
k
p1 q1 r1
p2 q2 r2
::
pk qk rk
The first line gives the number of track information n (1 ≤ n ≤ 3000) and the number of stations m (1 ≤ m ≤ 100).
The following n lines give information on the i-th line. As information on each line, the numbers ai, bi (1 ≤ ai, bi ≤ m) of the two stations connecting the lines, the toll costi (1 ≤ costi ≤ 1000), and the travel time timei (1 ≤ timei ≤ 1000) are given. I will. However, each station shall be numbered in order from 1 to m. If ai and bi are connected by railroad tracks, both ai to bi and bi to ai can be moved at the same rate and time.
The following line is given the number of queries k (1 ≤ k ≤ 200). The next k line is given the i-th query. For each query, the departure station pi, the arrival station qi, and the type of value to output ri (0 or 1) are given. Inquiries must have a route.
The number of datasets does not exceed 50.
Output
Outputs the minimum amount or minimum time on one line for each data set. When ri is 0, the minimum amount is output, and when ri is 1, the minimum time is output.
Example
Input
6 5
1 2 200 10
1 4 400 15
1 3 250 25
2 4 100 10
4 5 150 20
3 5 300 20
2
1 5 0
1 5 1
0 0
Output
450
35
Submitted Solution:
```
import copy as c
CEIL = 2000000000
def exploreMin(now, goal, mode, history, ans, lines):
#mode=0: MinCost;mode=1: MinTime
#print(lines)
if now == goal:
#print('??\????????±??????')
return ans
if now in history: return CEIL
minCostOrTime = CEIL
for destination in lines[now]:
exploreAns = exploreMin(destination[0], goal, mode, c.deepcopy(history)+[now],
ans+destination[mode+1], lines)
#print(exploreAns)
if minCostOrTime > exploreAns: minCostOrTime = exploreAns
return minCostOrTime
'''
def findMin(start, goal, mode):
minAnswer=100000
if minAnswer > xplore(start, goal, mode, []):
return minAnswer
'''
def dprint(a):
print('debug:', end='')
print(a)
def main():
input1 = input().split(' ')
#dprint(input1)
if input1[0] == '0': return True
lines=[[] for i in range(int(input1[1]))]
for lineIndex in range(int(input1[0])):
input2 = input().split(' ')
#print('debug:', end='')
#print(input2)
lines[int(input2[0])-1].append([int(input2[1])-1, int(input2[2]), int(input2[3])])
lines[int(input2[1])-1].append([int(input2[0])-1, int(input2[2]), int(input2[3])])
#print(lines[0][0][1])
setnum = int(input())
#a = '\n'
for out in range(setnum):
#if out==setnum-1: a=''
input3 = input().split(' ')
#print([].append(1))
print(exploreMin(int(input3[0])-1, int(input3[1])-1, int(input3[2]), [], 0, lines))
if __name__ == '__main__':
while True:
if main(): break
``` | instruction | 0 | 85,646 | 1 | 171,292 |
No | output | 1 | 85,646 | 1 | 171,293 |
Provide a correct Python 3 solution for this coding contest problem.
There are N cities in Republic of AtCoder. The size of the i-th city is A_{i}. Takahashi would like to build N-1 bidirectional roads connecting two cities so that any city can be reached from any other city by using these roads.
Assume that the cost of building a road connecting the i-th city and the j-th city is |i-j| \times D + A_{i} + A_{j}. For Takahashi, find the minimum possible total cost to achieve the objective.
Constraints
* 1 \leq N \leq 2 \times 10^5
* 1 \leq D \leq 10^9
* 1 \leq A_{i} \leq 10^9
* A_{i} and D are integers.
Input
Input is given from Standard Input in the following format:
N D
A_1 A_2 ... A_N
Output
Print the minimum possible total cost.
Examples
Input
3 1
1 100 1
Output
106
Input
3 1000
1 100 1
Output
2202
Input
6 14
25 171 7 1 17 162
Output
497
Input
12 5
43 94 27 3 69 99 56 25 8 15 46 8
Output
658 | instruction | 0 | 86,361 | 1 | 172,722 |
"Correct Solution:
```
from operator import itemgetter
import itertools
def inpl(): return list(map(int, input().split()))
def cost(x, y):
if x == y:
return float('inf')
return D * abs(x - y) + A[x] + A[y]
N, D = inpl()
A = inpl()
Right = [(v - i*D, i) for i, v in enumerate(A)]
Left = [(v + i*D, i) for i, v in enumerate(A)][::-1]
Right = list(map(itemgetter(1), itertools.accumulate(Right, min)))
Left = list(map(itemgetter(1), itertools.accumulate(Left, min)))[::-1]
ans = 0
hub = []
for i, (l, r) in enumerate(zip(Left, Right)) :
if i == l == r:
hub.append(i)
else:
ans += min(cost(i, r), cost(i, l))
print(ans + sum([cost(i, j) for i, j in zip(hub, hub[1:])]))
``` | output | 1 | 86,361 | 1 | 172,723 |
Provide a correct Python 3 solution for this coding contest problem.
There are N cities in Republic of AtCoder. The size of the i-th city is A_{i}. Takahashi would like to build N-1 bidirectional roads connecting two cities so that any city can be reached from any other city by using these roads.
Assume that the cost of building a road connecting the i-th city and the j-th city is |i-j| \times D + A_{i} + A_{j}. For Takahashi, find the minimum possible total cost to achieve the objective.
Constraints
* 1 \leq N \leq 2 \times 10^5
* 1 \leq D \leq 10^9
* 1 \leq A_{i} \leq 10^9
* A_{i} and D are integers.
Input
Input is given from Standard Input in the following format:
N D
A_1 A_2 ... A_N
Output
Print the minimum possible total cost.
Examples
Input
3 1
1 100 1
Output
106
Input
3 1000
1 100 1
Output
2202
Input
6 14
25 171 7 1 17 162
Output
497
Input
12 5
43 94 27 3 69 99 56 25 8 15 46 8
Output
658 | instruction | 0 | 86,362 | 1 | 172,724 |
"Correct Solution:
```
# E
N, D = map(int, input().split())
A_list = list(map(int, input().split()))
# minimum spanning tree
res = 0
# Prim based
B_list = [0]*N
for i in range(N):
B_list[i] = A_list[i] + D*i
C_list = [0]*N
for i in range(N):
C_list[i] = A_list[i] + D*(N-i)
# cummin seen from left
B_cummmin = [0]*N
R = B_list[N-1]
BA = N-1
for i in range(N-1, -1, -1):
if B_list[i] <= R:
R = B_list[i]
BA = i
B_cummmin[i] = BA
# cummin seen from right
C_cummmin = [0]*N
R = C_list[0]
CA = 0
for i in range(N):
if C_list[i] <= R:
R = C_list[i]
CA = i
C_cummmin[i] = CA
# start from 0
start = 0
while start < N-1:
end = B_cummmin[start+1]
target = C_cummmin[start]
res += D*(end - target) + A_list[target] + A_list[end]
for i in range(start+1, end):
ds = D*(i - target) + A_list[target] + A_list[i]
de = D*(end - i) + A_list[end] + A_list[i]
res += min(ds, de)
start = end
print(res)
``` | output | 1 | 86,362 | 1 | 172,725 |
Provide a correct Python 3 solution for this coding contest problem.
There are N cities in Republic of AtCoder. The size of the i-th city is A_{i}. Takahashi would like to build N-1 bidirectional roads connecting two cities so that any city can be reached from any other city by using these roads.
Assume that the cost of building a road connecting the i-th city and the j-th city is |i-j| \times D + A_{i} + A_{j}. For Takahashi, find the minimum possible total cost to achieve the objective.
Constraints
* 1 \leq N \leq 2 \times 10^5
* 1 \leq D \leq 10^9
* 1 \leq A_{i} \leq 10^9
* A_{i} and D are integers.
Input
Input is given from Standard Input in the following format:
N D
A_1 A_2 ... A_N
Output
Print the minimum possible total cost.
Examples
Input
3 1
1 100 1
Output
106
Input
3 1000
1 100 1
Output
2202
Input
6 14
25 171 7 1 17 162
Output
497
Input
12 5
43 94 27 3 69 99 56 25 8 15 46 8
Output
658 | instruction | 0 | 86,363 | 1 | 172,726 |
"Correct Solution:
```
import sys
read = sys.stdin.buffer.read
readline = sys.stdin.buffer.readline
readlines = sys.stdin.buffer.readlines
from heapq import heappush, heappop, heapify
from collections import defaultdict
"""
・最小値のある場所を調べる。左右にまたがる辺は結ばない。
・最小値の両隣は必ず最小値と結ぶ。
・結んだあと1点に縮約していく。
"""
N,D,*A = map(int,read().split())
A = [0] + A + [0] # 番兵
# (value<<32) + (index)
mask = (1<<32)-1
q = [(x<<32)+i for i,x in enumerate(A[1:-1],1)]
heapify(q)
removed = defaultdict(int)
cost = []
while q:
while q:
x = q[0]
if not removed[x]:
break
heappop(q); removed[x] -= 1
if not q:
break
x = heappop(q)
val,ind = x>>32, x&mask
L = A[ind-1]; R = A[ind+1]
if L:
cost.append(L+val+D)
# Lの値を書き換える
newL = val+D
if L > newL:
A[ind-1] = newL
removed[(L<<32)+(ind-1)] += 1
heappush(q,(newL<<32)+(ind-1))
if R:
cost.append(R+val+D)
# Lの値を書き換える
newR = val+D
if R > newR:
A[ind+1] = newR
removed[(R<<32)+(ind+1)] += 1
heappush(q,(newR<<32)+(ind+1))
A[ind] = 0
answer = sum(cost)
print(answer)
``` | output | 1 | 86,363 | 1 | 172,727 |
Provide a correct Python 3 solution for this coding contest problem.
There are N cities in Republic of AtCoder. The size of the i-th city is A_{i}. Takahashi would like to build N-1 bidirectional roads connecting two cities so that any city can be reached from any other city by using these roads.
Assume that the cost of building a road connecting the i-th city and the j-th city is |i-j| \times D + A_{i} + A_{j}. For Takahashi, find the minimum possible total cost to achieve the objective.
Constraints
* 1 \leq N \leq 2 \times 10^5
* 1 \leq D \leq 10^9
* 1 \leq A_{i} \leq 10^9
* A_{i} and D are integers.
Input
Input is given from Standard Input in the following format:
N D
A_1 A_2 ... A_N
Output
Print the minimum possible total cost.
Examples
Input
3 1
1 100 1
Output
106
Input
3 1000
1 100 1
Output
2202
Input
6 14
25 171 7 1 17 162
Output
497
Input
12 5
43 94 27 3 69 99 56 25 8 15 46 8
Output
658 | instruction | 0 | 86,364 | 1 | 172,728 |
"Correct Solution:
```
from itertools import accumulate
from operator import itemgetter
n, d = map(int, input().split())
aaa = list(map(int, input().split()))
costs_l = [(-i * d + a, i) for i, a in enumerate(aaa)]
costs_r = [(i * d + a, i) for i, a in enumerate(aaa)]
costs_l = list(accumulate(costs_l, min))
costs_r = list(accumulate(reversed(costs_r), min))
costs_r.reverse()
hubs = set(map(itemgetter(1), costs_l))
hubs.intersection_update(map(itemgetter(1), costs_r))
hubs.add(0)
hubs.add(n - 1)
hubs = sorted(hubs)
ans = sum(aaa) - aaa[-1]
s = hubs[0]
for t in hubs[1:]:
cls = costs_l[s][0]
crt = costs_r[t][0]
ans += crt - s * d
ans += sum(min(cls + i * d, crt - i * d) for i in range(s + 1, t))
s = t
print(ans)
``` | output | 1 | 86,364 | 1 | 172,729 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
There are N cities in Republic of AtCoder. The size of the i-th city is A_{i}. Takahashi would like to build N-1 bidirectional roads connecting two cities so that any city can be reached from any other city by using these roads.
Assume that the cost of building a road connecting the i-th city and the j-th city is |i-j| \times D + A_{i} + A_{j}. For Takahashi, find the minimum possible total cost to achieve the objective.
Constraints
* 1 \leq N \leq 2 \times 10^5
* 1 \leq D \leq 10^9
* 1 \leq A_{i} \leq 10^9
* A_{i} and D are integers.
Input
Input is given from Standard Input in the following format:
N D
A_1 A_2 ... A_N
Output
Print the minimum possible total cost.
Examples
Input
3 1
1 100 1
Output
106
Input
3 1000
1 100 1
Output
2202
Input
6 14
25 171 7 1 17 162
Output
497
Input
12 5
43 94 27 3 69 99 56 25 8 15 46 8
Output
658
Submitted Solution:
```
class Unionfindtree:
def __init__(self, number):
self.par = [i for i in range(number)]
self.rank = [0] * (number)
def find(self, x): # 親を探す
if self.par[x] == x:
return x
else:
self.par[x] = self.find(self.par[x])
return self.par[x]
def union(self, x, y): # x,yを繋げる
px = self.find(x)
py = self.find(y)
if px == py:
return
if self.rank[px] < self.rank[py]:
self.par[px] = py
else:
self.par[py] = px
if self.rank[px] == self.rank[py]:
self.rank[px] += 1
def connect(self, x, y): # 親が同じかみる
return self.find(x) == self.find(y)
class BIT():
def __init__(self, number):
self.n = number
self.list = [10**22] * (number + 1)
def add(self, i, x): # ith added x 1indexed
while i <= self.n:
self.list[i] = min(x,self.list[i])
i += i & -i
def search(self, i): # 1-i min
s = 10**22
while i > 0:
s = min(s,self.list[i])
i -= i & -i
return s
N,D=map(int,input().split())
A=[int(i) for i in input().split()]
lefttree = BIT(N)
dd={}
table=[]
for i in range(N):
lefttree.add(i+1,A[i]+(N-1-i)*D)
dd[A[i]+(N-1-i)*D]=i
if i>0:
s=lefttree.search(i)
y=dd[s]
table.append((A[i]+A[y]+D*abs(i-y),i,y))
#print(table)
righttree = BIT(N)
dr={}
for i in range(N-1,-1,-1):
righttree.add(N-i,A[i]+i*D)
dr[A[i]+i*D]=i
if i<N-1:
s=righttree.search(N-1-i)
#print(i, dr,s)
y=dr[s]
table.append((A[i]+A[y]+D*abs(i-y),i,y))
#print(table)
#print(table)
#print(dr)
table.sort()
uniontrees=Unionfindtree(N)
ans=0
for cost,s,t in table:
if not uniontrees.connect(s,t):
ans+=cost
uniontrees.union(s,t)
print(ans)
``` | instruction | 0 | 86,365 | 1 | 172,730 |
No | output | 1 | 86,365 | 1 | 172,731 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
There are N cities in Republic of AtCoder. The size of the i-th city is A_{i}. Takahashi would like to build N-1 bidirectional roads connecting two cities so that any city can be reached from any other city by using these roads.
Assume that the cost of building a road connecting the i-th city and the j-th city is |i-j| \times D + A_{i} + A_{j}. For Takahashi, find the minimum possible total cost to achieve the objective.
Constraints
* 1 \leq N \leq 2 \times 10^5
* 1 \leq D \leq 10^9
* 1 \leq A_{i} \leq 10^9
* A_{i} and D are integers.
Input
Input is given from Standard Input in the following format:
N D
A_1 A_2 ... A_N
Output
Print the minimum possible total cost.
Examples
Input
3 1
1 100 1
Output
106
Input
3 1000
1 100 1
Output
2202
Input
6 14
25 171 7 1 17 162
Output
497
Input
12 5
43 94 27 3 69 99 56 25 8 15 46 8
Output
658
Submitted Solution:
```
def judT(x, y):
xR = x
xC = 0
while T[xR] != xR:
xC += 1
xR = T[xR]
yR = y
yC = 0
while T[yR] != yR:
yC += 1
yR = T[yR]
if xR != yR:
if xC < yC:
T[xR] = yR
else:
T[yR] = xR
return xR != yR
N, D = tuple(map(int,input().split()))
A = tuple(map(int, input().split()))
rt = A[N - 1]
Ll = [N - 1]
k = N - 1
for i in range(N - 2, 0, -1):
t = A[i]
if rt > t - (k - i) * D :
Ll.append(i)
k = i
rt = t
rt = A[0]
Lr = [0]
k = 0
for i in range(1, N - 1):
t = A[i]
if rt > t + (k - i) * D:
Lr.append(i)
k = i
rt = t
Lr.append(N-1)
Ll = tuple(Ll)
Lr = tuple(Lr)
L = []
lC = -1
rC = 1
lCmax = -len(Ll) - 1
for i in range(N-1):
if i >= Ll[lC]:
lC -= 1
for j in range(lC, lCmax, -1):
t = Ll[j]
if A[i] >= A[t]:
L.append((A[i] + A[t] + (t - i) * D, i, t))
break
k = i + 1
if k > Lr[rC]:
rC += 1
for j in range(rC - 1, -1, -1):
t = Lr[j]
if A[k] > A[t]:
L.append((A[k] + A[t] + (k - t) * D, t, k))
break
L.sort()
T = [i for i in range(N)]
C = 0
A = 0
for i in L:
if judT(i[1], i[2]):
C += 1
A += i[0]
#print(i)
if C == N-1:
break
print(A)
``` | instruction | 0 | 86,366 | 1 | 172,732 |
No | output | 1 | 86,366 | 1 | 172,733 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
There are N cities in Republic of AtCoder. The size of the i-th city is A_{i}. Takahashi would like to build N-1 bidirectional roads connecting two cities so that any city can be reached from any other city by using these roads.
Assume that the cost of building a road connecting the i-th city and the j-th city is |i-j| \times D + A_{i} + A_{j}. For Takahashi, find the minimum possible total cost to achieve the objective.
Constraints
* 1 \leq N \leq 2 \times 10^5
* 1 \leq D \leq 10^9
* 1 \leq A_{i} \leq 10^9
* A_{i} and D are integers.
Input
Input is given from Standard Input in the following format:
N D
A_1 A_2 ... A_N
Output
Print the minimum possible total cost.
Examples
Input
3 1
1 100 1
Output
106
Input
3 1000
1 100 1
Output
2202
Input
6 14
25 171 7 1 17 162
Output
497
Input
12 5
43 94 27 3 69 99 56 25 8 15 46 8
Output
658
Submitted Solution:
```
# from typing import Callable
def connecting_cities(N: int, D: int, A: list) -> int:
edges = select_edges(N, D, A)
edges = sorted(edges, key=lambda x: x[2], reverse=True)
uft = UnionFindTree(N)
count = 0
while not len(edges) == 0:
u, v, d = edges.pop()
if not uft.same(u, v):
uft.summarize(u, v)
count += d
return count
def select_edges(N: int, D: int, A: list) -> list:
INF = 1 << 32
st_l = SegmentTree(N, lambda x, y: x if x[0] < y[0] else y, (INF, -1))
st_r = SegmentTree(N, lambda x, y: x if x[0] < y[0] else y, (INF, -1))
indexes_A = sorted([i for i in range(N)], key=lambda x: A[x])
edges = []
for i in indexes_A:
la, li = st_l.range(0, i)
if la < INF and li != -1:
edges.append((li, i, abs(i - li) * D + A[i] + A[li]))
ra, ri = st_r.range(i, N)
if ra < INF and ri != -1:
edges.append((ri, i, abs(i - ri) * D + A[i] + A[ri]))
st_l.update(i, (A[i] + (N - i) * D, i))
st_r.update(i, (A[i] + i * D, i))
# return [(i, j, abs(i - j) * D + A[i] + A[j])
# for i in range(N) for j in range(i + 1, N)]
return edges
class SegmentTree:
# def __init__(self, size: int, op: Callable[[any, any], any], init: any = 0):
def __init__(self, size, op, init):
"""initialize SegmentTree
:param size: Size of tree. This must be natural number.
:param op: Operator which compares two numbers. This function return the
representative value of two arguments.
:param init: The initial value of element of tree.
"""
if size < 1:
raise Exception('size must be greater than 0 (actual = %d)' % size)
self.__treesize = 1
self.__init = init
# tree size is the minimum number which is greater than or equal to
# designed `size` and is power of 2.
while self.__treesize < size:
self.__treesize *= 2
self.__size = self.__treesize
self.__treesize = self.__treesize * 2 - 1
self.__comp = op
# initialize tree
self.__tree = [init for _ in range(self.__treesize)]
def range(self, l: int, r: int) -> int:
"""Returns the representative value in range [l, r)
:param l: left value(include)
:param r: right value(not include)
:return: the representative value in range[l, r)
"""
return self.__range(l, r, 0, 0, self.__size)
def __range(self, l: int, r: int, k: int, kl: int, kr: int) -> int:
"""
:param l: left value (include)
:param r: right value (not include)
:param k: node index
:param kl: left value of node
:param kr: right value of node
"""
if kr <= l or r <= kl:
# no crossing
return self.__init
if l <= kl and kr <= r:
# including whole k's range
return self.__tree[k]
vl = self.__range(l, r, 2 * k + 1, kl, (kl + kr) // 2)
vr = self.__range(l, r, 2 * k + 2, (kl + kr) // 2, kr)
if vl is None:
return vr
if vr is None:
return vl
return self.__comp(vl, vr)
def update(self, index: int, val: int):
"""update value at self.__tree[index]'s value
"""
index += self.__size - 1
self.__tree[index] = val
while index > 0:
index = (index - 1) // 2
self.__tree[index] = self.__comp(
self.__tree[2*index + 1], self.__tree[2*index + 2])
def print(self):
"""for debug
"""
print(self.__tree)
class UnionFindTree:
def __init__(self, size: int):
"""UnionFindTreeを初期化します
:param size: サイズ
:return: UnionFindTree
"""
if size < 0:
raise Exception('size must be greater than 0.')
self.__parent = [-1] * size
def summarize(self, a: int, b: int):
"""aを含む木とbを含む木をまとめます
:param a: 木a
:param b: 木b
"""
a = self.__root(a)
b = self.__root(b)
if a != b:
self.__parent[b] = a
def __root(self, a: int) -> int:
"""aの根を求めます
:param a: 木の要素
:return: 根
"""
if self.__parent[a] == -1:
return a
else:
return self.__root(self.__parent[a])
def same(self, a: int, b: int) -> bool:
"""a と b が同じ木に属するかを判断します
:param a: 木
:param b: 木
:return: a と b が同じ木なら True。そうでないなら False。
"""
return self.__root(a) == self.__root(b)
if __name__ == "__main__":
N, D = [int(s) for s in input().split()]
A = [int(s) for s in input().split()]
ans = connecting_cities(N, D, A)
print(ans)
``` | instruction | 0 | 86,367 | 1 | 172,734 |
No | output | 1 | 86,367 | 1 | 172,735 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
There are N cities in Republic of AtCoder. The size of the i-th city is A_{i}. Takahashi would like to build N-1 bidirectional roads connecting two cities so that any city can be reached from any other city by using these roads.
Assume that the cost of building a road connecting the i-th city and the j-th city is |i-j| \times D + A_{i} + A_{j}. For Takahashi, find the minimum possible total cost to achieve the objective.
Constraints
* 1 \leq N \leq 2 \times 10^5
* 1 \leq D \leq 10^9
* 1 \leq A_{i} \leq 10^9
* A_{i} and D are integers.
Input
Input is given from Standard Input in the following format:
N D
A_1 A_2 ... A_N
Output
Print the minimum possible total cost.
Examples
Input
3 1
1 100 1
Output
106
Input
3 1000
1 100 1
Output
2202
Input
6 14
25 171 7 1 17 162
Output
497
Input
12 5
43 94 27 3 69 99 56 25 8 15 46 8
Output
658
Submitted Solution:
```
import numpy as np
InputData1 = input()
InputData2 = input()
Lines = [data.split(" ") for data in [InputData1, InputData2]]
InputNumbers = [int(numbers) for line in Lines for numbers in line]
N = InputNumbers[0]
D = InputNumbers[1]
A = InputNumbers[2:]
# print(N, D, A)
def NetworkMatrix(Num, vector):
matrix = np.empty((Num, Num))
for i in range(Num):
ai = np.empty(Num)
for j in range(Num):
if i < j:
aij = (j-i)*D + vector[i] + vector[j]
else:
aij = 0
ai[j] = aij
matrix[i] = ai
return matrix
def Explore(Num, matrix):
ResultMatrix = matrix
for i in range(Num):
# ResultVector[i] = min(matrix.T[i])
for j in range(Num):
for k in range(Num):
if i < j and j < k and min([matrix[i,j], matrix[j,k], matrix[i,k]]) != 0:
if matrix[i,j] >= matrix[j,k] and matrix[i,j] >= matrix[i,k]:
ResultMatrix[i,j] = 0
elif matrix[j,k] > matrix[i,j] and matrix[j,k] >= matrix[i,k]:
ResultMatrix[j,k] = 0
elif matrix[i,k] > matrix[i,j] and matrix[i,k] > matrix[j,k]:
ResultMatrix[i,k] = 0
if np.sum(ResultMatrix != matrix) != 0:
ResultMatrix = Explore(Num, matrix)
return ResultMatrix
Matrix = NetworkMatrix(N, A)
# print(Matrix)
# Raveled = Matrix.ravel()
# Answer = sum(sorted(Raveled)[:N-1])
AnswerMatrix=Explore(N, Matrix)
# print(AnswerMatrix)
print(int(np.sum(AnswerMatrix)))
``` | instruction | 0 | 86,368 | 1 | 172,736 |
No | output | 1 | 86,368 | 1 | 172,737 |
Provide a correct Python 3 solution for this coding contest problem.
I have n tickets for a train with a rabbit. Each ticket is numbered from 0 to n − 1, and you can use the k ticket to go to p⋅ak + q⋅bk station.
Rabbit wants to go to the all-you-can-eat carrot shop at the station m station ahead of the current station, but wants to walk as short as possible. The stations are lined up at regular intervals. When using, how many stations can a rabbit walk to reach the store?
Input
1 ≤ n, m, a, b, p, q ≤ 1 000 000 000 000 (integer)
Output
Output the number of rabbits that can reach the store on foot at the minimum number of stations in one line.
Examples
Input
6 200 2 3 4 5
Output
1
Input
6 1 2 3 4 5
Output
1 | instruction | 0 | 86,507 | 1 | 173,014 |
"Correct Solution:
```
import sys
readline = sys.stdin.readline
write = sys.stdout.write
def solve():
N, M, A, B, P, Q = map(int, readline().split())
ans = M
if A == B == 1:
v = P+Q
k = min(N, M // v)
ans = min(ans, M - k*v)
if k+1 <= N:
ans = min(ans, (k+1)*v - M)
else:
k = 0
V = []
va = 1; vb = 1
while k < N:
v = P*va + Q*vb
V.append(v)
if v > M:
break
va *= A; vb *= B
k += 1
def make(S):
s = {0}
for v in S:
t = set(s)
for e in s:
t.add(e + v)
s = t
return sorted(s)
L = len(V)
S0 = make(V[:L//2]); S1 = make(V[L//2:])
t = len(S1)-1
for s0 in S0:
while t > 0 and s0 + S1[t] > M:
t -= 1
if s0 + S1[t] <= M:
ans = min(ans, M - s0 - S1[t])
t = len(S1)-1
for s0 in S0:
while t > 0 and s0 + S1[t-1] >= M:
t -= 1
if s0 + S1[t] >= M:
ans = min(ans, s0 + S1[t] - M)
write("%d\n" % ans)
solve()
``` | output | 1 | 86,507 | 1 | 173,015 |
Provide a correct Python 3 solution for this coding contest problem.
I have n tickets for a train with a rabbit. Each ticket is numbered from 0 to n − 1, and you can use the k ticket to go to p⋅ak + q⋅bk station.
Rabbit wants to go to the all-you-can-eat carrot shop at the station m station ahead of the current station, but wants to walk as short as possible. The stations are lined up at regular intervals. When using, how many stations can a rabbit walk to reach the store?
Input
1 ≤ n, m, a, b, p, q ≤ 1 000 000 000 000 (integer)
Output
Output the number of rabbits that can reach the store on foot at the minimum number of stations in one line.
Examples
Input
6 200 2 3 4 5
Output
1
Input
6 1 2 3 4 5
Output
1 | instruction | 0 | 86,508 | 1 | 173,016 |
"Correct Solution:
```
def solve():
n,m,a,b,p,q = map(int,input().split())
if a==1 and b==1:
if (p+q)*n <= m:
return m - (p+q)*n
else:
k = m//(p+q)
return min(m-k*(p+q),(k+1)*(p+q)-m)
else:
ans = m
for i in range(min(n-1,40),-1,-1):
f = p*(a**i) + q*(b**i)
if m < f:
ans = min(ans, f-m)
else:
m -= f
ans = min(ans,m)
return ans
def main():
print(solve())
if __name__ == '__main__':
main()
``` | output | 1 | 86,508 | 1 | 173,017 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.