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 a correct Python 3 solution for this coding contest problem.
J: City
Santa decides to deliver a present to a city.
The city has a rectangular shape divided into north-south $ H $ parcels x east-west $ W $ parcels, with one house delivering gifts to each parcel.
The $ X $ th section from the north and the $ Y $ th section from the west are represented by $ (X, Y) $.
Santa moves under the following conditions.
* First, get off at block $ (S, T) $ and start from this place.
* You can move to the adjacent sections in the north, south, east, and west with one move, and you cannot move outside the city.
* You will never enter the area you visited once.
Determine if Santa can visit all the houses in the city.
input
$ H, W, S, T $ are given separated by blanks.
output
Output "Yes" if Santa can visit all the homes in the city, otherwise output "No".
Constraint
* $ H, W $ are integers greater than or equal to $ 2 $ and less than or equal to $ 1 \ 000 \ 000 \ 000 $
* $ S $ is an integer greater than or equal to $ 1 $ and less than or equal to $ H $
* $ T $ is an integer greater than or equal to $ 1 $ and less than or equal to $ W $
Input example 1
4 5 2 3
Output example 1
Yes
For example, you can go to the figure.
<image>
Input example 2
3 3 1 2
Output example 2
No
Example
Input
4 5 2 3
Output
Yes | instruction | 0 | 90,933 | 1 | 181,866 |
"Correct Solution:
```
h,w,s,t = map(int,input().split())
if h%2 == 1 and w%2 == 1:
if (s+t)%2 == 1:
print("No")
else:
print("Yes")
else:
print("Yes")
``` | output | 1 | 90,933 | 1 | 181,867 |
Provide a correct Python 3 solution for this coding contest problem.
J: City
Santa decides to deliver a present to a city.
The city has a rectangular shape divided into north-south $ H $ parcels x east-west $ W $ parcels, with one house delivering gifts to each parcel.
The $ X $ th section from the north and the $ Y $ th section from the west are represented by $ (X, Y) $.
Santa moves under the following conditions.
* First, get off at block $ (S, T) $ and start from this place.
* You can move to the adjacent sections in the north, south, east, and west with one move, and you cannot move outside the city.
* You will never enter the area you visited once.
Determine if Santa can visit all the houses in the city.
input
$ H, W, S, T $ are given separated by blanks.
output
Output "Yes" if Santa can visit all the homes in the city, otherwise output "No".
Constraint
* $ H, W $ are integers greater than or equal to $ 2 $ and less than or equal to $ 1 \ 000 \ 000 \ 000 $
* $ S $ is an integer greater than or equal to $ 1 $ and less than or equal to $ H $
* $ T $ is an integer greater than or equal to $ 1 $ and less than or equal to $ W $
Input example 1
4 5 2 3
Output example 1
Yes
For example, you can go to the figure.
<image>
Input example 2
3 3 1 2
Output example 2
No
Example
Input
4 5 2 3
Output
Yes | instruction | 0 | 90,934 | 1 | 181,868 |
"Correct Solution:
```
h,w,x,y=map(int,input().split())
print(["Yes","No"][h*w%2==1 and(x+y)%2==1])
``` | output | 1 | 90,934 | 1 | 181,869 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Vasya plays FreeDiv. In this game he manages a huge state, which has n cities and m two-way roads between them. Unfortunately, not from every city you can reach any other one moving along these roads. Therefore Vasya decided to divide the state into provinces so that in every province, one could reach from every city all the cities of the province, but there are no roads between provinces.
Unlike other turn-based strategies, in FreeDiv a player has the opportunity to build tunnels between cities. The tunnels are two-way roads along which one can move armies undetected by the enemy. However, no more than one tunnel can be connected to each city. As for Vasya, he wants to build a network of tunnels so that any pair of cities in his state were reachable by some path consisting of roads and a tunnels. But at that no more than k tunnels are connected to each province (otherwise, the province will be difficult to keep in case other provinces are captured by enemy armies).
Vasya discovered that maybe he will not be able to build such a network for the current condition of the state. Maybe he'll have first to build several roads between cities in different provinces to merge the provinces. Your task is to determine the minimum number of roads Vasya needs to build so that it was possible to build the required network of tunnels in the resulting state.
Input
The first line contains three integers n, m and k (1 ≤ n, k ≤ 106, 0 ≤ m ≤ 106). Each of the next m lines contains two integers. They are the numbers of cities connected by a corresponding road. No road connects city to itself and there is at most one road between each pair of cities.
Output
Print a single number, the minimum number of additional roads.
Examples
Input
3 3 2
1 2
2 3
3 1
Output
0
Input
4 2 2
1 2
3 4
Output
0
Input
4 0 2
Output
1
Note
In the first example only one province exists, so it is not necessary to build any tunnels or roads.
In the second example two provinces exist. It is possible to merge the provinces by building a tunnel between cities 1 and 3.
In the third example at least one additional road is necessary. For example it is possible to build additional road between cities 1 and 2 and build two tunnels between cities 1 and 3, 2 and 4 after that.
Submitted Solution:
```
LmBCxDiGSKuTWIF = map
LmBCxDiGSKuTWIv = int
LmBCxDiGSKuTWIe = input
LmBCxDiGSKuTWIR = range
LmBCxDiGSKuTWIX = print
n, m, k = LmBCxDiGSKuTWIF(LmBCxDiGSKuTWIv, LmBCxDiGSKuTWIe().split())
c = [-1]*n
def LmBCxDiGSKuTWIo(x):
p = x
while c[p] >= 0:
p = c[p]
while c[x] >= 0:
t = c[x]
c[x] = p
x = t
return p
for i in LmBCxDiGSKuTWIR(m):
x, y = LmBCxDiGSKuTWIe().split()
f = LmBCxDiGSKuTWIo(LmBCxDiGSKuTWIv(x)-1)
t = LmBCxDiGSKuTWIo(LmBCxDiGSKuTWIv(y)-1)
if f == t:
continue
if(c[f] & 1):
f, t = t, f
c[t] += c[f]
c[f] = t
l, s, q = 0, 2, 0
for i in LmBCxDiGSKuTWIR(n):
if c[i] >= 0:
continue
j = k if c[i] < -k else-c[i]
if j == 1:
l += 1
else:
s += j-2
q += 1
if l == 1:
LmBCxDiGSKuTWIX(0)
elif k == 1:
LmBCxDiGSKuTWIX(q-2)
elif l <= s:
LmBCxDiGSKuTWIX(0)
else:
LmBCxDiGSKuTWIX((l-s+1)/2)
``` | instruction | 0 | 91,332 | 1 | 182,664 |
No | output | 1 | 91,332 | 1 | 182,665 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Misha and Grisha are funny boys, so they like to use new underground. The underground has n stations connected with n - 1 routes so that each route connects two stations, and it is possible to reach every station from any other.
The boys decided to have fun and came up with a plan. Namely, in some day in the morning Misha will ride the underground from station s to station f by the shortest path, and will draw with aerosol an ugly text "Misha was here" on every station he will pass through (including s and f). After that on the same day at evening Grisha will ride from station t to station f by the shortest path and will count stations with Misha's text. After that at night the underground workers will wash the texts out, because the underground should be clean.
The boys have already chosen three stations a, b and c for each of several following days, one of them should be station s on that day, another should be station f, and the remaining should be station t. They became interested how they should choose these stations s, f, t so that the number Grisha will count is as large as possible. They asked you for help.
Input
The first line contains two integers n and q (2 ≤ n ≤ 105, 1 ≤ q ≤ 105) — the number of stations and the number of days.
The second line contains n - 1 integers p2, p3, ..., pn (1 ≤ pi ≤ n). The integer pi means that there is a route between stations pi and i. It is guaranteed that it's possible to reach every station from any other.
The next q lines contains three integers a, b and c each (1 ≤ a, b, c ≤ n) — the ids of stations chosen by boys for some day. Note that some of these ids could be same.
Output
Print q lines. In the i-th of these lines print the maximum possible number Grisha can get counting when the stations s, t and f are chosen optimally from the three stations on the i-th day.
Examples
Input
3 2
1 1
1 2 3
2 3 3
Output
2
3
Input
4 1
1 2 3
1 2 3
Output
2
Note
In the first example on the first day if s = 1, f = 2, t = 3, Misha would go on the route 1 <image> 2, and Grisha would go on the route 3 <image> 1 <image> 2. He would see the text at the stations 1 and 2. On the second day, if s = 3, f = 2, t = 3, both boys would go on the route 3 <image> 1 <image> 2. Grisha would see the text at 3 stations.
In the second examle if s = 1, f = 3, t = 2, Misha would go on the route 1 <image> 2 <image> 3, and Grisha would go on the route 2 <image> 3 and would see the text at both stations. | instruction | 0 | 91,365 | 1 | 182,730 |
Tags: dfs and similar, graphs, trees
Correct Solution:
```
# by the authority of GOD author: manhar singh sachdev #
import os,sys
from io import BytesIO, IOBase
def pre(n,path,lim):
# lim = n.bit_length()
up = [[-1]*(lim+1) for _ in range(n)]
st,visi,height = [0],[1]+[0]*(n-1),[0]*n
start,finish,time = [0]*n,[0]*n,0
while len(st):
x = st[-1]
y,j = up[x][0],0
while y != -1:
up[x][j] = y
y = up[y][j]
j += 1
while len(path[x]) and visi[path[x][-1]]:
path[x].pop()
if not len(path[x]):
time += 1
finish[x] = time
st.pop()
else:
i = path[x].pop()
st.append(i)
time += 1
visi[i],start[i],up[i][0],height[i] = 1,time,x,height[x]+1
return start,finish,up,height
def is_ancestor(u,v,start,finish):
return start[u] <= start[v] and finish[u] >= finish[v]
def lca(u,v,up,start,finish,lim):
if is_ancestor(u,v,start,finish):
return u
if is_ancestor(v,u,start,finish):
return v
for i in range(lim,-1,-1):
if up[u][i] != -1 and not is_ancestor(up[u][i],v,start,finish):
u = up[u][i]
return up[u][0]
def solve(s,f,t,up,start,finish,lim,height):
a = lca(s,f,up,start,finish,lim)
b = lca(t,f,up,start,finish,lim)
ans = height[f]-max(height[a],height[b])+1
if a == b:
x = lca(s,t,up,start,finish,lim)
ans += height[x]-height[a]
return ans
def main():
n,q = map(int,input().split())
path = [[] for _ in range(n)]
for ind,i in enumerate(map(int,input().split())):
path[ind+1].append(i-1)
path[i-1].append(ind+1)
lim = n.bit_length()
start,finish,up,height = pre(n,path,lim)
for _ in range(q):
a,b,c = map(lambda xx:int(xx)-1,input().split())
print(max(solve(a,b,c,up,start,finish,lim,height),
solve(a,c,b,up,start,finish,lim,height),
solve(b,a,c,up,start,finish,lim,height)))
# Fast IO Region
BUFSIZE = 8192
class FastIO(IOBase):
newlines = 0
def __init__(self, file):
self._fd = file.fileno()
self.buffer = BytesIO()
self.writable = "x" in file.mode or "r" not in file.mode
self.write = self.buffer.write if self.writable else None
def read(self):
while True:
b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
if not b:
break
ptr = self.buffer.tell()
self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr)
self.newlines = 0
return self.buffer.read()
def readline(self):
while self.newlines == 0:
b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
self.newlines = b.count(b"\n") + (not b)
ptr = self.buffer.tell()
self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr)
self.newlines -= 1
return self.buffer.readline()
def flush(self):
if self.writable:
os.write(self._fd, self.buffer.getvalue())
self.buffer.truncate(0), self.buffer.seek(0)
class IOWrapper(IOBase):
def __init__(self, file):
self.buffer = FastIO(file)
self.flush = self.buffer.flush
self.writable = self.buffer.writable
self.write = lambda s: self.buffer.write(s.encode("ascii"))
self.read = lambda: self.buffer.read().decode("ascii")
self.readline = lambda: self.buffer.readline().decode("ascii")
sys.stdin, sys.stdout = IOWrapper(sys.stdin), IOWrapper(sys.stdout)
input = lambda: sys.stdin.readline().rstrip("\r\n")
if __name__ == "__main__":
main()
``` | output | 1 | 91,365 | 1 | 182,731 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Misha and Grisha are funny boys, so they like to use new underground. The underground has n stations connected with n - 1 routes so that each route connects two stations, and it is possible to reach every station from any other.
The boys decided to have fun and came up with a plan. Namely, in some day in the morning Misha will ride the underground from station s to station f by the shortest path, and will draw with aerosol an ugly text "Misha was here" on every station he will pass through (including s and f). After that on the same day at evening Grisha will ride from station t to station f by the shortest path and will count stations with Misha's text. After that at night the underground workers will wash the texts out, because the underground should be clean.
The boys have already chosen three stations a, b and c for each of several following days, one of them should be station s on that day, another should be station f, and the remaining should be station t. They became interested how they should choose these stations s, f, t so that the number Grisha will count is as large as possible. They asked you for help.
Input
The first line contains two integers n and q (2 ≤ n ≤ 105, 1 ≤ q ≤ 105) — the number of stations and the number of days.
The second line contains n - 1 integers p2, p3, ..., pn (1 ≤ pi ≤ n). The integer pi means that there is a route between stations pi and i. It is guaranteed that it's possible to reach every station from any other.
The next q lines contains three integers a, b and c each (1 ≤ a, b, c ≤ n) — the ids of stations chosen by boys for some day. Note that some of these ids could be same.
Output
Print q lines. In the i-th of these lines print the maximum possible number Grisha can get counting when the stations s, t and f are chosen optimally from the three stations on the i-th day.
Examples
Input
3 2
1 1
1 2 3
2 3 3
Output
2
3
Input
4 1
1 2 3
1 2 3
Output
2
Note
In the first example on the first day if s = 1, f = 2, t = 3, Misha would go on the route 1 <image> 2, and Grisha would go on the route 3 <image> 1 <image> 2. He would see the text at the stations 1 and 2. On the second day, if s = 3, f = 2, t = 3, both boys would go on the route 3 <image> 1 <image> 2. Grisha would see the text at 3 stations.
In the second examle if s = 1, f = 3, t = 2, Misha would go on the route 1 <image> 2 <image> 3, and Grisha would go on the route 2 <image> 3 and would see the text at both stations. | instruction | 0 | 91,366 | 1 | 182,732 |
Tags: dfs and similar, graphs, trees
Correct Solution:
```
# by the authority of GOD author: manhar singh sachdev #
import os,sys
from io import BytesIO, IOBase
def euler_path(n,path):
height = [0]*n+[10**10]
euler,st,visi,he = [],[0],[1]+[0]*(n-1),0
first = [-1]*n
while len(st):
x = st[-1]
euler.append(x)
if first[x] == -1:
first[x] = len(euler)-1
while len(path[x]) and visi[path[x][-1]]:
path[x].pop()
if not len(path[x]):
he -= 1
st.pop()
else:
i = path[x].pop()
he += 1
st.append(i)
height[i],visi[i] = he,1
return height,euler,first
def cons(euler,height):
n = len(euler)
xx = n.bit_length()
dp = [[n]*n for _ in range(xx)]
dp[0] = euler
for i in range(1,xx):
for j in range(n-(1<<i)+1):
a,b = dp[i-1][j],dp[i-1][j+(1<<(i-1))]
dp[i][j] = a if height[a] < height[b] else b
return dp
def lca(l,r,dp,height,first):
l,r = first[l],first[r]
if l > r:
l,r = r,l
xx1 = (r-l+1).bit_length()-1
a,b = dp[xx1][l],dp[xx1][r-(1<<xx1)+1]
return a if height[a] < height[b] else b
def solve(s,f,t,dp,height,first):
a = lca(s,f,dp,height,first)
b = lca(t,f,dp,height,first)
ans = height[f]-max(height[a],height[b])+1
if a == b:
x = lca(s,t,dp,height,first)
ans += height[x]-height[a]
return ans
def main():
n,q = map(int,input().split())
path = [[] for _ in range(n)]
for ind,i in enumerate(map(int,input().split())):
path[ind+1].append(i-1)
path[i-1].append(ind+1)
height,euler,first = euler_path(n,path)
dp = cons(euler,height)
for _ in range(q):
a,b,c = map(lambda xx:int(xx)-1,input().split())
print(max(solve(a,b,c,dp,height,first),
solve(a,c,b,dp,height,first),
solve(b,a,c,dp,height,first)))
# Fast IO Region
BUFSIZE = 8192
class FastIO(IOBase):
newlines = 0
def __init__(self, file):
self._fd = file.fileno()
self.buffer = BytesIO()
self.writable = "x" in file.mode or "r" not in file.mode
self.write = self.buffer.write if self.writable else None
def read(self):
while True:
b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
if not b:
break
ptr = self.buffer.tell()
self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr)
self.newlines = 0
return self.buffer.read()
def readline(self):
while self.newlines == 0:
b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
self.newlines = b.count(b"\n") + (not b)
ptr = self.buffer.tell()
self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr)
self.newlines -= 1
return self.buffer.readline()
def flush(self):
if self.writable:
os.write(self._fd, self.buffer.getvalue())
self.buffer.truncate(0), self.buffer.seek(0)
class IOWrapper(IOBase):
def __init__(self, file):
self.buffer = FastIO(file)
self.flush = self.buffer.flush
self.writable = self.buffer.writable
self.write = lambda s: self.buffer.write(s.encode("ascii"))
self.read = lambda: self.buffer.read().decode("ascii")
self.readline = lambda: self.buffer.readline().decode("ascii")
sys.stdin, sys.stdout = IOWrapper(sys.stdin), IOWrapper(sys.stdout)
input = lambda: sys.stdin.readline().rstrip("\r\n")
if __name__ == "__main__":
main()
``` | output | 1 | 91,366 | 1 | 182,733 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Misha and Grisha are funny boys, so they like to use new underground. The underground has n stations connected with n - 1 routes so that each route connects two stations, and it is possible to reach every station from any other.
The boys decided to have fun and came up with a plan. Namely, in some day in the morning Misha will ride the underground from station s to station f by the shortest path, and will draw with aerosol an ugly text "Misha was here" on every station he will pass through (including s and f). After that on the same day at evening Grisha will ride from station t to station f by the shortest path and will count stations with Misha's text. After that at night the underground workers will wash the texts out, because the underground should be clean.
The boys have already chosen three stations a, b and c for each of several following days, one of them should be station s on that day, another should be station f, and the remaining should be station t. They became interested how they should choose these stations s, f, t so that the number Grisha will count is as large as possible. They asked you for help.
Input
The first line contains two integers n and q (2 ≤ n ≤ 105, 1 ≤ q ≤ 105) — the number of stations and the number of days.
The second line contains n - 1 integers p2, p3, ..., pn (1 ≤ pi ≤ n). The integer pi means that there is a route between stations pi and i. It is guaranteed that it's possible to reach every station from any other.
The next q lines contains three integers a, b and c each (1 ≤ a, b, c ≤ n) — the ids of stations chosen by boys for some day. Note that some of these ids could be same.
Output
Print q lines. In the i-th of these lines print the maximum possible number Grisha can get counting when the stations s, t and f are chosen optimally from the three stations on the i-th day.
Examples
Input
3 2
1 1
1 2 3
2 3 3
Output
2
3
Input
4 1
1 2 3
1 2 3
Output
2
Note
In the first example on the first day if s = 1, f = 2, t = 3, Misha would go on the route 1 <image> 2, and Grisha would go on the route 3 <image> 1 <image> 2. He would see the text at the stations 1 and 2. On the second day, if s = 3, f = 2, t = 3, both boys would go on the route 3 <image> 1 <image> 2. Grisha would see the text at 3 stations.
In the second examle if s = 1, f = 3, t = 2, Misha would go on the route 1 <image> 2 <image> 3, and Grisha would go on the route 2 <image> 3 and would see the text at both stations. | instruction | 0 | 91,367 | 1 | 182,734 |
Tags: dfs and similar, graphs, trees
Correct Solution:
```
import os
import sys
from io import BytesIO, IOBase
from types import GeneratorType
from collections import defaultdict
BUFSIZE = 8192
class FastIO(IOBase):
newlines = 0
def __init__(self, file):
self._fd = file.fileno()
self.buffer = BytesIO()
self.writable = "x" in file.mode or "r" not in file.mode
self.write = self.buffer.write if self.writable else None
def read(self):
while True:
b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
if not b:
break
ptr = self.buffer.tell()
self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr)
self.newlines = 0
return self.buffer.read()
def readline(self):
while self.newlines == 0:
b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
self.newlines = b.count(b"\n") + (not b)
ptr = self.buffer.tell()
self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr)
self.newlines -= 1
return self.buffer.readline()
def flush(self):
if self.writable:
os.write(self._fd, self.buffer.getvalue())
self.buffer.truncate(0), self.buffer.seek(0)
class IOWrapper(IOBase):
def __init__(self, file):
self.buffer = FastIO(file)
self.flush = self.buffer.flush
self.writable = self.buffer.writable
self.write = lambda s: self.buffer.write(s.encode("ascii"))
self.read = lambda: self.buffer.read().decode("ascii")
self.readline = lambda: self.buffer.readline().decode("ascii")
sys.stdin, sys.stdout = IOWrapper(sys.stdin), IOWrapper(sys.stdout)
input = lambda: sys.stdin.readline().rstrip("\r\n")
sys.setrecursionlimit(3*10**5)
def bootstrap(f, stack=[]):
def wrappedfunc(*args, **kwargs):
if stack:
return f(*args, **kwargs)
else:
to = f(*args, **kwargs)
while True:
if type(to) is GeneratorType:
stack.append(to)
to = next(to)
else:
stack.pop()
if not stack:
break
to = stack[-1].send(to)
return to
return wrappedfunc
MA=10**5+1
level=20
tree=[[] for i in range(MA)]
depth=[0 for i in range(MA)]
parent=[[0 for i in range(level)] for j in range(MA)]
@bootstrap
def dfs(cur,prev):
depth[cur] = depth[prev] + 1
parent[cur][0] = prev
for i in range(len(tree[cur])):
if (tree[cur][i] != prev):
yield dfs(tree[cur][i], cur)
yield
def precomputeSparseMatrix(n):
for i in range(1,level):
for node in range(1,n+1):
if (parent[node][i-1] != -1):
parent[node][i] =parent[parent[node][i-1]][i-1]
def lca(u,v):
if (depth[v] < depth[u]):
u,v=v,u
diff = depth[v] - depth[u]
for i in range(level):
if ((diff >> i) & 1):
v = parent[v][i]
if (u == v):
return u
i=level-1
while(i>=0):
if (parent[u][i] != parent[v][i]):
u = parent[u][i]
v = parent[v][i]
i+=-1
return parent[u][0]
def add(a,b):
tree[a].append(b)
tree[b].append(a)
def res(s,t,f):
p=lca(t,f)
q=lca(s,f)
if p==q:
r=depth[lca(s,t)]-depth[p]
return min(depth[p] + depth[f] - 2 * depth[p] + 1+r, depth[q] + depth[f] - 2 * depth[q] + 1+r)
return min(depth[p]+depth[f]-2*depth[p]+1,depth[q]+depth[f]-2*depth[q]+1)
n,q=map(int,input().split())
p=list(map(int,input().split()))
for j in range(n-1):
tree[p[j]].append(j+2)
tree[j+2].append(p[j])
dfs(1,0)
precomputeSparseMatrix(n)
for j in range(q):
a,b,c=map(int,input().split())
print(max(res(a,b,c),res(a,c,b),res(b,c,a)))
``` | output | 1 | 91,367 | 1 | 182,735 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Misha and Grisha are funny boys, so they like to use new underground. The underground has n stations connected with n - 1 routes so that each route connects two stations, and it is possible to reach every station from any other.
The boys decided to have fun and came up with a plan. Namely, in some day in the morning Misha will ride the underground from station s to station f by the shortest path, and will draw with aerosol an ugly text "Misha was here" on every station he will pass through (including s and f). After that on the same day at evening Grisha will ride from station t to station f by the shortest path and will count stations with Misha's text. After that at night the underground workers will wash the texts out, because the underground should be clean.
The boys have already chosen three stations a, b and c for each of several following days, one of them should be station s on that day, another should be station f, and the remaining should be station t. They became interested how they should choose these stations s, f, t so that the number Grisha will count is as large as possible. They asked you for help.
Input
The first line contains two integers n and q (2 ≤ n ≤ 105, 1 ≤ q ≤ 105) — the number of stations and the number of days.
The second line contains n - 1 integers p2, p3, ..., pn (1 ≤ pi ≤ n). The integer pi means that there is a route between stations pi and i. It is guaranteed that it's possible to reach every station from any other.
The next q lines contains three integers a, b and c each (1 ≤ a, b, c ≤ n) — the ids of stations chosen by boys for some day. Note that some of these ids could be same.
Output
Print q lines. In the i-th of these lines print the maximum possible number Grisha can get counting when the stations s, t and f are chosen optimally from the three stations on the i-th day.
Examples
Input
3 2
1 1
1 2 3
2 3 3
Output
2
3
Input
4 1
1 2 3
1 2 3
Output
2
Note
In the first example on the first day if s = 1, f = 2, t = 3, Misha would go on the route 1 <image> 2, and Grisha would go on the route 3 <image> 1 <image> 2. He would see the text at the stations 1 and 2. On the second day, if s = 3, f = 2, t = 3, both boys would go on the route 3 <image> 1 <image> 2. Grisha would see the text at 3 stations.
In the second examle if s = 1, f = 3, t = 2, Misha would go on the route 1 <image> 2 <image> 3, and Grisha would go on the route 2 <image> 3 and would see the text at both stations.
Submitted Solution:
```
#!/usr/local/bin/python3
import sys
from collections import defaultdict, deque
n, q = map(int, input().split())
graph = defaultdict(set)
graph_encoded = map(int, input().split())
for n1, n2 in enumerate(graph_encoded, 2):
graph[n1].add(n2)
graph[n2].add(n1)
cache = defaultdict(set)
def shortest_distance(graph, a, b):
frontier = deque([(a, [a])])
seen = set([a])
while frontier:
current_node, path = frontier.popleft()
if (current_node, b) in cache:
return path + cache[(current_node, b)][1:]
if current_node == b:
break
for nn in graph[current_node]:
if nn in seen:
continue
seen.add(nn)
frontier.append((nn, path + [nn]))
return path
for _ in range(q):
a, b, c = map(int, input().split())
if (a == b) and (b == c):
print(1)
continue
ab = shortest_distance(graph, a, b)
for i, x in enumerate(ab):
cache[(x, b)] = ab[i:]
ac = shortest_distance(graph, a, c)
cb = shortest_distance(graph, c, b)
print(max(len(set(ab) & set(cb)), len(set(ac) & set(cb))))
``` | instruction | 0 | 91,368 | 1 | 182,736 |
No | output | 1 | 91,368 | 1 | 182,737 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Misha and Grisha are funny boys, so they like to use new underground. The underground has n stations connected with n - 1 routes so that each route connects two stations, and it is possible to reach every station from any other.
The boys decided to have fun and came up with a plan. Namely, in some day in the morning Misha will ride the underground from station s to station f by the shortest path, and will draw with aerosol an ugly text "Misha was here" on every station he will pass through (including s and f). After that on the same day at evening Grisha will ride from station t to station f by the shortest path and will count stations with Misha's text. After that at night the underground workers will wash the texts out, because the underground should be clean.
The boys have already chosen three stations a, b and c for each of several following days, one of them should be station s on that day, another should be station f, and the remaining should be station t. They became interested how they should choose these stations s, f, t so that the number Grisha will count is as large as possible. They asked you for help.
Input
The first line contains two integers n and q (2 ≤ n ≤ 105, 1 ≤ q ≤ 105) — the number of stations and the number of days.
The second line contains n - 1 integers p2, p3, ..., pn (1 ≤ pi ≤ n). The integer pi means that there is a route between stations pi and i. It is guaranteed that it's possible to reach every station from any other.
The next q lines contains three integers a, b and c each (1 ≤ a, b, c ≤ n) — the ids of stations chosen by boys for some day. Note that some of these ids could be same.
Output
Print q lines. In the i-th of these lines print the maximum possible number Grisha can get counting when the stations s, t and f are chosen optimally from the three stations on the i-th day.
Examples
Input
3 2
1 1
1 2 3
2 3 3
Output
2
3
Input
4 1
1 2 3
1 2 3
Output
2
Note
In the first example on the first day if s = 1, f = 2, t = 3, Misha would go on the route 1 <image> 2, and Grisha would go on the route 3 <image> 1 <image> 2. He would see the text at the stations 1 and 2. On the second day, if s = 3, f = 2, t = 3, both boys would go on the route 3 <image> 1 <image> 2. Grisha would see the text at 3 stations.
In the second examle if s = 1, f = 3, t = 2, Misha would go on the route 1 <image> 2 <image> 3, and Grisha would go on the route 2 <image> 3 and would see the text at both stations.
Submitted Solution:
```
import os
import sys
from io import BytesIO, IOBase
from collections import defaultdict
BUFSIZE = 8192
class FastIO(IOBase):
newlines = 0
def __init__(self, file):
self._fd = file.fileno()
self.buffer = BytesIO()
self.writable = "x" in file.mode or "r" not in file.mode
self.write = self.buffer.write if self.writable else None
def read(self):
while True:
b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
if not b:
break
ptr = self.buffer.tell()
self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr)
self.newlines = 0
return self.buffer.read()
def readline(self):
while self.newlines == 0:
b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
self.newlines = b.count(b"\n") + (not b)
ptr = self.buffer.tell()
self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr)
self.newlines -= 1
return self.buffer.readline()
def flush(self):
if self.writable:
os.write(self._fd, self.buffer.getvalue())
self.buffer.truncate(0), self.buffer.seek(0)
class IOWrapper(IOBase):
def __init__(self, file):
self.buffer = FastIO(file)
self.flush = self.buffer.flush
self.writable = self.buffer.writable
self.write = lambda s: self.buffer.write(s.encode("ascii"))
self.read = lambda: self.buffer.read().decode("ascii")
self.readline = lambda: self.buffer.readline().decode("ascii")
sys.stdin, sys.stdout = IOWrapper(sys.stdin), IOWrapper(sys.stdout)
input = lambda: sys.stdin.readline().rstrip("\r\n")
MA=10**5+1
level=18
tree=[[] for i in range(MA)]
depth=[0 for i in range(MA)]
parent=[[0 for i in range(level)] for j in range(MA)]
def dfs(cur,prev):
depth[cur] = depth[prev] + 1
parent[cur][0] = prev
for i in range(len(tree[cur])):
if (tree[cur][i] != prev):
dfs(tree[cur][i], cur)
def precomputeSparseMatrix(n):
for i in range(1,level):
for node in range(1,n+1):
if (parent[node][i-1] != -1):
parent[node][i] =parent[parent[node][i-1]][i-1]
def lca(u,v):
if (depth[v] < depth[u]):
u,v=v,u
diff = depth[v] - depth[u]
for i in range(level):
if ((diff >> i) & 1):
v = parent[v][i]
if (u == v):
return u
i=level-1
while(i>=0):
if (parent[u][i] != parent[v][i]):
u = parent[u][i]
v = parent[v][i]
i+=-1
return parent[u][0]
def add(a,b):
tree[a].append(b)
tree[b].append(a)
def res(s,t,f):
p=lca(t,f)
q=lca(s,f)
if p==q:
r=min(depth[s],depth[t])-depth[p]
return min(depth[p] + depth[f] - 2 * depth[p] + 1+r, depth[q] + depth[f] - 2 * depth[q] + 1+r)
return min(depth[p]+depth[f]-2*depth[p]+1,depth[q]+depth[f]-2*depth[q]+1)
n,q=map(int,input().split())
p=list(map(int,input().split()))
for j in range(n-1):
tree[p[j]].append(j+2)
tree[j+2].append(p[j])
dfs(1,0)
precomputeSparseMatrix(n)
for j in range(q):
a,b,c=map(int,input().split())
print(max(res(a,b,c),res(a,c,b),res(b,c,a)))
``` | instruction | 0 | 91,369 | 1 | 182,738 |
No | output | 1 | 91,369 | 1 | 182,739 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Misha and Grisha are funny boys, so they like to use new underground. The underground has n stations connected with n - 1 routes so that each route connects two stations, and it is possible to reach every station from any other.
The boys decided to have fun and came up with a plan. Namely, in some day in the morning Misha will ride the underground from station s to station f by the shortest path, and will draw with aerosol an ugly text "Misha was here" on every station he will pass through (including s and f). After that on the same day at evening Grisha will ride from station t to station f by the shortest path and will count stations with Misha's text. After that at night the underground workers will wash the texts out, because the underground should be clean.
The boys have already chosen three stations a, b and c for each of several following days, one of them should be station s on that day, another should be station f, and the remaining should be station t. They became interested how they should choose these stations s, f, t so that the number Grisha will count is as large as possible. They asked you for help.
Input
The first line contains two integers n and q (2 ≤ n ≤ 105, 1 ≤ q ≤ 105) — the number of stations and the number of days.
The second line contains n - 1 integers p2, p3, ..., pn (1 ≤ pi ≤ n). The integer pi means that there is a route between stations pi and i. It is guaranteed that it's possible to reach every station from any other.
The next q lines contains three integers a, b and c each (1 ≤ a, b, c ≤ n) — the ids of stations chosen by boys for some day. Note that some of these ids could be same.
Output
Print q lines. In the i-th of these lines print the maximum possible number Grisha can get counting when the stations s, t and f are chosen optimally from the three stations on the i-th day.
Examples
Input
3 2
1 1
1 2 3
2 3 3
Output
2
3
Input
4 1
1 2 3
1 2 3
Output
2
Note
In the first example on the first day if s = 1, f = 2, t = 3, Misha would go on the route 1 <image> 2, and Grisha would go on the route 3 <image> 1 <image> 2. He would see the text at the stations 1 and 2. On the second day, if s = 3, f = 2, t = 3, both boys would go on the route 3 <image> 1 <image> 2. Grisha would see the text at 3 stations.
In the second examle if s = 1, f = 3, t = 2, Misha would go on the route 1 <image> 2 <image> 3, and Grisha would go on the route 2 <image> 3 and would see the text at both stations.
Submitted Solution:
```
n, q = map(int, input().split())
p = [[0 for i in range(n)] for j in range(n)]
def Dijkstra_path(s, e):
global n, p
path = [0] * n
d = [1000000] * n
d[s] = 0
u = [False] * n
for i in range(n):
v = -1
for j in range(n):
if v == -1 or (d[j] < d[v] and not u[j]):
v = j
u[v] = True
for to in range(n):
if p[v][to] and d[v] + 1 < d[to]:
d[to] = d[v] + 1
path[to] = v
ans = [0] * n
ans[e] = 1
curr = e
while curr != s:
curr = path[curr]
ans[curr] = 1
return ans
for i, pi in enumerate(input().split()):
p[i + 1][int(pi) - 1] = 1
p[int(pi) - 1][i + 1] = 1
p[i][i] = 1
p[-1][-1] = 1
while q:
a, b, c = map(int, input().split())
a -= 1
b -= 1
c -= 1
max_matches = 0
for x, y, z in [[a, b, c], [b, a, c], [a, c, b], [c, a, b], [b, c, a], [c, b, a]]:
curr_matches = 0
for Misha, Grisha in zip(Dijkstra_path(x, z), Dijkstra_path(y, z)):
if Misha and Grisha:
curr_matches += 1
max_matches = max(max_matches, curr_matches)
print(max_matches)
q -= 1
``` | instruction | 0 | 91,370 | 1 | 182,740 |
No | output | 1 | 91,370 | 1 | 182,741 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Misha and Grisha are funny boys, so they like to use new underground. The underground has n stations connected with n - 1 routes so that each route connects two stations, and it is possible to reach every station from any other.
The boys decided to have fun and came up with a plan. Namely, in some day in the morning Misha will ride the underground from station s to station f by the shortest path, and will draw with aerosol an ugly text "Misha was here" on every station he will pass through (including s and f). After that on the same day at evening Grisha will ride from station t to station f by the shortest path and will count stations with Misha's text. After that at night the underground workers will wash the texts out, because the underground should be clean.
The boys have already chosen three stations a, b and c for each of several following days, one of them should be station s on that day, another should be station f, and the remaining should be station t. They became interested how they should choose these stations s, f, t so that the number Grisha will count is as large as possible. They asked you for help.
Input
The first line contains two integers n and q (2 ≤ n ≤ 105, 1 ≤ q ≤ 105) — the number of stations and the number of days.
The second line contains n - 1 integers p2, p3, ..., pn (1 ≤ pi ≤ n). The integer pi means that there is a route between stations pi and i. It is guaranteed that it's possible to reach every station from any other.
The next q lines contains three integers a, b and c each (1 ≤ a, b, c ≤ n) — the ids of stations chosen by boys for some day. Note that some of these ids could be same.
Output
Print q lines. In the i-th of these lines print the maximum possible number Grisha can get counting when the stations s, t and f are chosen optimally from the three stations on the i-th day.
Examples
Input
3 2
1 1
1 2 3
2 3 3
Output
2
3
Input
4 1
1 2 3
1 2 3
Output
2
Note
In the first example on the first day if s = 1, f = 2, t = 3, Misha would go on the route 1 <image> 2, and Grisha would go on the route 3 <image> 1 <image> 2. He would see the text at the stations 1 and 2. On the second day, if s = 3, f = 2, t = 3, both boys would go on the route 3 <image> 1 <image> 2. Grisha would see the text at 3 stations.
In the second examle if s = 1, f = 3, t = 2, Misha would go on the route 1 <image> 2 <image> 3, and Grisha would go on the route 2 <image> 3 and would see the text at both stations.
Submitted Solution:
```
import os
import sys
from io import BytesIO, IOBase
from collections import defaultdict
BUFSIZE = 8192
class FastIO(IOBase):
newlines = 0
def __init__(self, file):
self._fd = file.fileno()
self.buffer = BytesIO()
self.writable = "x" in file.mode or "r" not in file.mode
self.write = self.buffer.write if self.writable else None
def read(self):
while True:
b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
if not b:
break
ptr = self.buffer.tell()
self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr)
self.newlines = 0
return self.buffer.read()
def readline(self):
while self.newlines == 0:
b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
self.newlines = b.count(b"\n") + (not b)
ptr = self.buffer.tell()
self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr)
self.newlines -= 1
return self.buffer.readline()
def flush(self):
if self.writable:
os.write(self._fd, self.buffer.getvalue())
self.buffer.truncate(0), self.buffer.seek(0)
class IOWrapper(IOBase):
def __init__(self, file):
self.buffer = FastIO(file)
self.flush = self.buffer.flush
self.writable = self.buffer.writable
self.write = lambda s: self.buffer.write(s.encode("ascii"))
self.read = lambda: self.buffer.read().decode("ascii")
self.readline = lambda: self.buffer.readline().decode("ascii")
sys.stdin, sys.stdout = IOWrapper(sys.stdin), IOWrapper(sys.stdout)
input = lambda: sys.stdin.readline().rstrip("\r\n")
MA=10**5+1
level=18
tree=[[] for i in range(MA)]
depth=[0 for i in range(MA)]
parent=[[0 for i in range(level)] for j in range(MA)]
def dfs(cur,prev):
depth[cur] = depth[prev] + 1
parent[cur][0] = prev
for i in range(len(tree[cur])):
if (tree[cur][i] != prev):
dfs(tree[cur][i], cur)
def precomputeSparseMatrix(n):
for i in range(1,level):
for node in range(1,n+1):
if (parent[node][i-1] != -1):
parent[node][i] =parent[parent[node][i-1]][i-1]
def lca(u,v):
if (depth[v] < depth[u]):
u,v=v,u
diff = depth[v] - depth[u]
for i in range(level):
if ((diff >> i) & 1):
v = parent[v][i]
if (u == v):
return u
i=level-1
while(i>=0):
if (parent[u][i] != parent[v][i]):
u = parent[u][i]
v = parent[v][i]
i+=-1
return parent[u][0]
def add(a,b):
tree[a].append(b)
tree[b].append(a)
def res(s,t,f):
k=lca(s,t)
p=lca(f,t)
q=lca(s,f)
if k==s and p==t:
return depth[f]-depth[t]+1
if k==t and q==s:
return depth[f] - depth[s] + 1
if p == t:
return depth[f] - depth[t] + 1
if q==s:
return depth[f] - depth[s] + 1
if k==s:
if q==f and q==s:
return 1
if k==t:
if q == f and p==t:
return 1
if k==s and lca(p,s)==s:
return depth[f]-depth[p]+1
if k==t and lca(q,t)==t:
return depth[f] - depth[q] + 1
if lca(q,k)==k:
return depth[f] - depth[q] + 1
if lca(p,k)==k:
return depth[f] - depth[p] + 1
return depth[f]+depth[k]-2*depth[lca(k,f)]+1
n,q=map(int,input().split())
p=list(map(int,input().split()))
for j in range(n-1):
tree[p[j]].append(j+2)
tree[j+2].append(p[j])
dfs(1,0)
precomputeSparseMatrix(n)
for j in range(q):
a,b,c=map(int,input().split())
print(max(res(a,b,c),res(a,c,b),res(b,c,a)))
``` | instruction | 0 | 91,371 | 1 | 182,742 |
No | output | 1 | 91,371 | 1 | 182,743 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Country of Metropolia is holding Olympiad of Metrpolises soon. It mean that all jury members of the olympiad should meet together in Metropolis (the capital of the country) for the problem preparation process.
There are n + 1 cities consecutively numbered from 0 to n. City 0 is Metropolis that is the meeting point for all jury members. For each city from 1 to n there is exactly one jury member living there. Olympiad preparation is a long and demanding process that requires k days of work. For all of these k days each of the n jury members should be present in Metropolis to be able to work on problems.
You know the flight schedule in the country (jury members consider themselves important enough to only use flights for transportation). All flights in Metropolia are either going to Metropolis or out of Metropolis. There are no night flights in Metropolia, or in the other words, plane always takes off at the same day it arrives. On his arrival day and departure day jury member is not able to discuss the olympiad. All flights in Megapolia depart and arrive at the same day.
Gather everybody for k days in the capital is a hard objective, doing that while spending the minimum possible money is even harder. Nevertheless, your task is to arrange the cheapest way to bring all of the jury members to Metrpolis, so that they can work together for k days and then send them back to their home cities. Cost of the arrangement is defined as a total cost of tickets for all used flights. It is allowed for jury member to stay in Metropolis for more than k days.
Input
The first line of input contains three integers n, m and k (1 ≤ n ≤ 105, 0 ≤ m ≤ 105, 1 ≤ k ≤ 106).
The i-th of the following m lines contains the description of the i-th flight defined by four integers di, fi, ti and ci (1 ≤ di ≤ 106, 0 ≤ fi ≤ n, 0 ≤ ti ≤ n, 1 ≤ ci ≤ 106, exactly one of fi and ti equals zero), the day of departure (and arrival), the departure city, the arrival city and the ticket cost.
Output
Output the only integer that is the minimum cost of gathering all jury members in city 0 for k days and then sending them back to their home cities.
If it is impossible to gather everybody in Metropolis for k days and then send them back to their home cities, output "-1" (without the quotes).
Examples
Input
2 6 5
1 1 0 5000
3 2 0 5500
2 2 0 6000
15 0 2 9000
9 0 1 7000
8 0 2 6500
Output
24500
Input
2 4 5
1 2 0 5000
2 1 0 4500
2 1 0 3000
8 0 1 6000
Output
-1
Note
The optimal way to gather everybody in Metropolis in the first sample test is to use flights that take place on days 1, 2, 8 and 9. The only alternative option is to send jury member from second city back home on day 15, that would cost 2500 more.
In the second sample it is impossible to send jury member from city 2 back home from Metropolis. | instruction | 0 | 91,372 | 1 | 182,744 |
Tags: greedy, sortings, two pointers
Correct Solution:
```
N,M,K = map(int,input().split())
INF = 10**6+1
from collections import defaultdict
incoming = defaultdict(list)
outgoing = defaultdict(list)
for _ in range(M):
d,f,t,c = map(int,input().split())
if t == 0:
incoming[d].append((c,f-1))
if f == 0:
outgoing[d].append((c,t-1))
incoming_dates = sorted(incoming.keys())
outgoing_dates = sorted(outgoing.keys(),reverse=True)
Li = []
mark = [False]*N
cnt = 0
costs = [0]*N
total_cost = 0
for d in incoming_dates:
for c,x in incoming[d]:
if mark[x]:
if costs[x] > c:
total_cost += c-costs[x]
costs[x] = c
else:
mark[x] = True
cnt += 1
costs[x] = c
total_cost += c
if cnt == N:
Li.append((d,total_cost))
Lo = []
mark = [False]*N
cnt = 0
costs = [0]*N
total_cost = 0
for d in outgoing_dates:
for c,x in outgoing[d]:
if mark[x]:
if costs[x] > c:
total_cost += c-costs[x]
costs[x] = c
else:
mark[x] = True
cnt += 1
costs[x] = c
total_cost += c
if cnt == N:
Lo.append((d,total_cost))
Lo.reverse()
if not Li or not Lo:
print(-1)
exit()
# print(Li,Lo)
from bisect import bisect
best = float('inf')
for d,c in Li:
i = bisect(Lo,(d+K+1,0))
if i >= len(Lo):
break
else:
best = min(best,c+Lo[i][1])
if best == float('inf'):
print(-1)
else:
print(best)
``` | output | 1 | 91,372 | 1 | 182,745 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Country of Metropolia is holding Olympiad of Metrpolises soon. It mean that all jury members of the olympiad should meet together in Metropolis (the capital of the country) for the problem preparation process.
There are n + 1 cities consecutively numbered from 0 to n. City 0 is Metropolis that is the meeting point for all jury members. For each city from 1 to n there is exactly one jury member living there. Olympiad preparation is a long and demanding process that requires k days of work. For all of these k days each of the n jury members should be present in Metropolis to be able to work on problems.
You know the flight schedule in the country (jury members consider themselves important enough to only use flights for transportation). All flights in Metropolia are either going to Metropolis or out of Metropolis. There are no night flights in Metropolia, or in the other words, plane always takes off at the same day it arrives. On his arrival day and departure day jury member is not able to discuss the olympiad. All flights in Megapolia depart and arrive at the same day.
Gather everybody for k days in the capital is a hard objective, doing that while spending the minimum possible money is even harder. Nevertheless, your task is to arrange the cheapest way to bring all of the jury members to Metrpolis, so that they can work together for k days and then send them back to their home cities. Cost of the arrangement is defined as a total cost of tickets for all used flights. It is allowed for jury member to stay in Metropolis for more than k days.
Input
The first line of input contains three integers n, m and k (1 ≤ n ≤ 105, 0 ≤ m ≤ 105, 1 ≤ k ≤ 106).
The i-th of the following m lines contains the description of the i-th flight defined by four integers di, fi, ti and ci (1 ≤ di ≤ 106, 0 ≤ fi ≤ n, 0 ≤ ti ≤ n, 1 ≤ ci ≤ 106, exactly one of fi and ti equals zero), the day of departure (and arrival), the departure city, the arrival city and the ticket cost.
Output
Output the only integer that is the minimum cost of gathering all jury members in city 0 for k days and then sending them back to their home cities.
If it is impossible to gather everybody in Metropolis for k days and then send them back to their home cities, output "-1" (without the quotes).
Examples
Input
2 6 5
1 1 0 5000
3 2 0 5500
2 2 0 6000
15 0 2 9000
9 0 1 7000
8 0 2 6500
Output
24500
Input
2 4 5
1 2 0 5000
2 1 0 4500
2 1 0 3000
8 0 1 6000
Output
-1
Note
The optimal way to gather everybody in Metropolis in the first sample test is to use flights that take place on days 1, 2, 8 and 9. The only alternative option is to send jury member from second city back home on day 15, that would cost 2500 more.
In the second sample it is impossible to send jury member from city 2 back home from Metropolis. | instruction | 0 | 91,373 | 1 | 182,746 |
Tags: greedy, sortings, two pointers
Correct Solution:
```
# ---------------------------iye ha aam zindegi---------------------------------------------
import math
import heapq, bisect
import sys
from collections import deque, defaultdict
from fractions import Fraction
mod = 10 ** 9 + 7
mod1 = 998244353
# ------------------------------warmup----------------------------
import os
import sys
from io import BytesIO, IOBase
BUFSIZE = 8192
class FastIO(IOBase):
newlines = 0
def __init__(self, file):
self._fd = file.fileno()
self.buffer = BytesIO()
self.writable = "x" in file.mode or "r" not in file.mode
self.write = self.buffer.write if self.writable else None
def read(self):
while True:
b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
if not b:
break
ptr = self.buffer.tell()
self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr)
self.newlines = 0
return self.buffer.read()
def readline(self):
while self.newlines == 0:
b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
self.newlines = b.count(b"\n") + (not b)
ptr = self.buffer.tell()
self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr)
self.newlines -= 1
return self.buffer.readline()
def flush(self):
if self.writable:
os.write(self._fd, self.buffer.getvalue())
self.buffer.truncate(0), self.buffer.seek(0)
class IOWrapper(IOBase):
def __init__(self, file):
self.buffer = FastIO(file)
self.flush = self.buffer.flush
self.writable = self.buffer.writable
self.write = lambda s: self.buffer.write(s.encode("ascii"))
self.read = lambda: self.buffer.read().decode("ascii")
self.readline = lambda: self.buffer.readline().decode("ascii")
sys.stdin, sys.stdout = IOWrapper(sys.stdin), IOWrapper(sys.stdout)
input = lambda: sys.stdin.readline().rstrip("\r\n")
# -------------------game starts now----------------------------------------------------import math
class TreeNode:
def __init__(self, k, v):
self.key = k
self.value = v
self.left = None
self.right = None
self.parent = None
self.height = 1
self.num_left = 1
self.num_total = 1
class AvlTree:
def __init__(self):
self._tree = None
def add(self, k, v):
if not self._tree:
self._tree = TreeNode(k, v)
return
node = self._add(k, v)
if node:
self._rebalance(node)
def _add(self, k, v):
node = self._tree
while node:
if k < node.key:
if node.left:
node = node.left
else:
node.left = TreeNode(k, v)
node.left.parent = node
return node.left
elif node.key < k:
if node.right:
node = node.right
else:
node.right = TreeNode(k, v)
node.right.parent = node
return node.right
else:
node.value = v
return
@staticmethod
def get_height(x):
return x.height if x else 0
@staticmethod
def get_num_total(x):
return x.num_total if x else 0
def _rebalance(self, node):
n = node
while n:
lh = self.get_height(n.left)
rh = self.get_height(n.right)
n.height = max(lh, rh) + 1
balance_factor = lh - rh
n.num_total = 1 + self.get_num_total(n.left) + self.get_num_total(n.right)
n.num_left = 1 + self.get_num_total(n.left)
if balance_factor > 1:
if self.get_height(n.left.left) < self.get_height(n.left.right):
self._rotate_left(n.left)
self._rotate_right(n)
elif balance_factor < -1:
if self.get_height(n.right.right) < self.get_height(n.right.left):
self._rotate_right(n.right)
self._rotate_left(n)
else:
n = n.parent
def _remove_one(self, node):
"""
Side effect!!! Changes node. Node should have exactly one child
"""
replacement = node.left or node.right
if node.parent:
if AvlTree._is_left(node):
node.parent.left = replacement
else:
node.parent.right = replacement
replacement.parent = node.parent
node.parent = None
else:
self._tree = replacement
replacement.parent = None
node.left = None
node.right = None
node.parent = None
self._rebalance(replacement)
def _remove_leaf(self, node):
if node.parent:
if AvlTree._is_left(node):
node.parent.left = None
else:
node.parent.right = None
self._rebalance(node.parent)
else:
self._tree = None
node.parent = None
node.left = None
node.right = None
def remove(self, k):
node = self._get_node(k)
if not node:
return
if AvlTree._is_leaf(node):
self._remove_leaf(node)
return
if node.left and node.right:
nxt = AvlTree._get_next(node)
node.key = nxt.key
node.value = nxt.value
if self._is_leaf(nxt):
self._remove_leaf(nxt)
else:
self._remove_one(nxt)
self._rebalance(node)
else:
self._remove_one(node)
def get(self, k):
node = self._get_node(k)
return node.value if node else -1
def _get_node(self, k):
if not self._tree:
return None
node = self._tree
while node:
if k < node.key:
node = node.left
elif node.key < k:
node = node.right
else:
return node
return None
def get_at(self, pos):
x = pos + 1
node = self._tree
while node:
if x < node.num_left:
node = node.left
elif node.num_left < x:
x -= node.num_left
node = node.right
else:
return (node.key, node.value)
raise IndexError("Out of ranges")
@staticmethod
def _is_left(node):
return node.parent.left and node.parent.left == node
@staticmethod
def _is_leaf(node):
return node.left is None and node.right is None
def _rotate_right(self, node):
if not node.parent:
self._tree = node.left
node.left.parent = None
elif AvlTree._is_left(node):
node.parent.left = node.left
node.left.parent = node.parent
else:
node.parent.right = node.left
node.left.parent = node.parent
bk = node.left.right
node.left.right = node
node.parent = node.left
node.left = bk
if bk:
bk.parent = node
node.height = max(self.get_height(node.left), self.get_height(node.right)) + 1
node.num_total = 1 + self.get_num_total(node.left) + self.get_num_total(node.right)
node.num_left = 1 + self.get_num_total(node.left)
def _rotate_left(self, node):
if not node.parent:
self._tree = node.right
node.right.parent = None
elif AvlTree._is_left(node):
node.parent.left = node.right
node.right.parent = node.parent
else:
node.parent.right = node.right
node.right.parent = node.parent
bk = node.right.left
node.right.left = node
node.parent = node.right
node.right = bk
if bk:
bk.parent = node
node.height = max(self.get_height(node.left), self.get_height(node.right)) + 1
node.num_total = 1 + self.get_num_total(node.left) + self.get_num_total(node.right)
node.num_left = 1 + self.get_num_total(node.left)
@staticmethod
def _get_next(node):
if not node.right:
return node.parent
n = node.right
while n.left:
n = n.left
return n
avl=AvlTree()
#-----------------------------------------------binary seacrh tree---------------------------------------
class SegmentTree1:
def __init__(self, data, default='z', func=lambda a, b: min(a ,b)):
"""initialize the segment tree with data"""
self._default = default
self._func = func
self._len = len(data)
self._size = _size = 1 << (self._len - 1).bit_length()
self.data = [default] * (2 * _size)
self.data[_size:_size + self._len] = data
for i in reversed(range(_size)):
self.data[i] = func(self.data[i + i], self.data[i + i + 1])
def __delitem__(self, idx):
self[idx] = self._default
def __getitem__(self, idx):
return self.data[idx + self._size]
def __setitem__(self, idx, value):
idx += self._size
self.data[idx] = value
idx >>= 1
while idx:
self.data[idx] = self._func(self.data[2 * idx], self.data[2 * idx + 1])
idx >>= 1
def __len__(self):
return self._len
def query(self, start, stop):
if start == stop:
return self.__getitem__(start)
stop += 1
start += self._size
stop += self._size
res = self._default
while start < stop:
if start & 1:
res = self._func(res, self.data[start])
start += 1
if stop & 1:
stop -= 1
res = self._func(res, self.data[stop])
start >>= 1
stop >>= 1
return res
def __repr__(self):
return "SegmentTree({0})".format(self.data)
# -------------------game starts now----------------------------------------------------import math
class SegmentTree:
def __init__(self, data, default=0, func=lambda a, b: a + b):
"""initialize the segment tree with data"""
self._default = default
self._func = func
self._len = len(data)
self._size = _size = 1 << (self._len - 1).bit_length()
self.data = [default] * (2 * _size)
self.data[_size:_size + self._len] = data
for i in reversed(range(_size)):
self.data[i] = func(self.data[i + i], self.data[i + i + 1])
def __delitem__(self, idx):
self[idx] = self._default
def __getitem__(self, idx):
return self.data[idx + self._size]
def __setitem__(self, idx, value):
idx += self._size
self.data[idx] = value
idx >>= 1
while idx:
self.data[idx] = self._func(self.data[2 * idx], self.data[2 * idx + 1])
idx >>= 1
def __len__(self):
return self._len
def query(self, start, stop):
if start == stop:
return self.__getitem__(start)
stop += 1
start += self._size
stop += self._size
res = self._default
while start < stop:
if start & 1:
res = self._func(res, self.data[start])
start += 1
if stop & 1:
stop -= 1
res = self._func(res, self.data[stop])
start >>= 1
stop >>= 1
return res
def __repr__(self):
return "SegmentTree({0})".format(self.data)
# -------------------------------iye ha chutiya zindegi-------------------------------------
class Factorial:
def __init__(self, MOD):
self.MOD = MOD
self.factorials = [1, 1]
self.invModulos = [0, 1]
self.invFactorial_ = [1, 1]
def calc(self, n):
if n <= -1:
print("Invalid argument to calculate n!")
print("n must be non-negative value. But the argument was " + str(n))
exit()
if n < len(self.factorials):
return self.factorials[n]
nextArr = [0] * (n + 1 - len(self.factorials))
initialI = len(self.factorials)
prev = self.factorials[-1]
m = self.MOD
for i in range(initialI, n + 1):
prev = nextArr[i - initialI] = prev * i % m
self.factorials += nextArr
return self.factorials[n]
def inv(self, n):
if n <= -1:
print("Invalid argument to calculate n^(-1)")
print("n must be non-negative value. But the argument was " + str(n))
exit()
p = self.MOD
pi = n % p
if pi < len(self.invModulos):
return self.invModulos[pi]
nextArr = [0] * (n + 1 - len(self.invModulos))
initialI = len(self.invModulos)
for i in range(initialI, min(p, n + 1)):
next = -self.invModulos[p % i] * (p // i) % p
self.invModulos.append(next)
return self.invModulos[pi]
def invFactorial(self, n):
if n <= -1:
print("Invalid argument to calculate (n^(-1))!")
print("n must be non-negative value. But the argument was " + str(n))
exit()
if n < len(self.invFactorial_):
return self.invFactorial_[n]
self.inv(n) # To make sure already calculated n^-1
nextArr = [0] * (n + 1 - len(self.invFactorial_))
initialI = len(self.invFactorial_)
prev = self.invFactorial_[-1]
p = self.MOD
for i in range(initialI, n + 1):
prev = nextArr[i - initialI] = (prev * self.invModulos[i % p]) % p
self.invFactorial_ += nextArr
return self.invFactorial_[n]
class Combination:
def __init__(self, MOD):
self.MOD = MOD
self.factorial = Factorial(MOD)
def ncr(self, n, k):
if k < 0 or n < k:
return 0
k = min(k, n - k)
f = self.factorial
return f.calc(n) * f.invFactorial(max(n - k, k)) * f.invFactorial(min(k, n - k)) % self.MOD
# --------------------------------------iye ha combinations ka zindegi---------------------------------
def powm(a, n, m):
if a == 1 or n == 0:
return 1
if n % 2 == 0:
s = powm(a, n // 2, m)
return s * s % m
else:
return a * powm(a, n - 1, m) % m
# --------------------------------------iye ha power ka zindegi---------------------------------
def sort_list(list1, list2):
zipped_pairs = zip(list2, list1)
z = [x for _, x in sorted(zipped_pairs)]
return z
# --------------------------------------------------product----------------------------------------
def product(l):
por = 1
for i in range(len(l)):
por *= l[i]
return por
# --------------------------------------------------binary----------------------------------------
def binarySearchCount(arr, n, key):
left = 0
right = n - 1
count = 0
while (left <= right):
mid = int((right + left)/ 2)
# Check if middle element is
# less than or equal to key
if (arr[mid]<=key):
count = mid+1
left = mid + 1
# If key is smaller, ignore right half
else:
right = mid - 1
return count
# --------------------------------------------------binary----------------------------------------
def countdig(n):
c = 0
while (n > 0):
n //= 10
c += 1
return c
def countGreater( arr,n, k):
l = 0
r = n - 1
# Stores the index of the left most element
# from the array which is greater than k
leftGreater = n
# Finds number of elements greater than k
while (l <= r):
m = int(l + (r - l) / 2)
if (arr[m] >= k):
leftGreater = m
r = m - 1
# If mid element is less than
# or equal to k update l
else:
l = m + 1
# Return the count of elements
# greater than k
return (n - leftGreater)
# --------------------------------------------------binary------------------------------------
n,m,k=map(int,input().split())
incom=defaultdict(list)
outgo=defaultdict(list)
for i in range(m):
d,f,t,cost=map(int,input().split())
if t==0:
incom[d].append((f,cost))
else:
outgo[d].append((t,cost))
cost=[9999999999999999999]*n
cou=0
total_cost=0
l=[]
for i in sorted(incom.keys()):
for j in range(len(incom[i])):
if cost[incom[i][j][0]-1]==9999999999999999999:
total_cost+=incom[i][j][1]
cou+=1
else:
total_cost+=min(0,incom[i][j][1]-cost[incom[i][j][0]-1])
cost[incom[i][j][0]-1]=min(cost[incom[i][j][0]-1],incom[i][j][1])
if cou==n:
l.append((i,total_cost))
if max(cost)==9999999999999999999:
print(-1)
sys.exit(0)
cost=[9999999999999999999]*n
cou=0
total_cost=0
l1=[]
for i in sorted(outgo.keys(),reverse=True):
for j in range(len(outgo[i])):
if cost[outgo[i][j][0]-1]==9999999999999999999:
total_cost+=outgo[i][j][1]
cou+=1
else:
total_cost+=min(0,outgo[i][j][1]-cost[outgo[i][j][0]-1])
cost[outgo[i][j][0]-1]=min(cost[outgo[i][j][0]-1],outgo[i][j][1])
if cou==n:
l1.append((i,total_cost))
if max(cost)==9999999999999999999:
print(-1)
sys.exit(0)
l1.reverse()
mint=[0]*len(l1)
mint[-1]=l1[-1][1]
for i in range(len(l1)-2,-1,-1):
mint[i]=min(l1[i][1],mint[i+1])
ans=9999999999999999
t=0
#print(l1,l,mint)
for i in range(len(l)):
d=l[i][0]+k+1
#print(d)
f=0
if t==len(l1):
break
while(d>l1[t][0]):
t+=1
if t==len(l1):
f=1
break
if f==0:
ans=min(ans,l[i][1]+mint[t])
if ans==9999999999999999:
print(-1)
else:
print(ans)
``` | output | 1 | 91,373 | 1 | 182,747 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Country of Metropolia is holding Olympiad of Metrpolises soon. It mean that all jury members of the olympiad should meet together in Metropolis (the capital of the country) for the problem preparation process.
There are n + 1 cities consecutively numbered from 0 to n. City 0 is Metropolis that is the meeting point for all jury members. For each city from 1 to n there is exactly one jury member living there. Olympiad preparation is a long and demanding process that requires k days of work. For all of these k days each of the n jury members should be present in Metropolis to be able to work on problems.
You know the flight schedule in the country (jury members consider themselves important enough to only use flights for transportation). All flights in Metropolia are either going to Metropolis or out of Metropolis. There are no night flights in Metropolia, or in the other words, plane always takes off at the same day it arrives. On his arrival day and departure day jury member is not able to discuss the olympiad. All flights in Megapolia depart and arrive at the same day.
Gather everybody for k days in the capital is a hard objective, doing that while spending the minimum possible money is even harder. Nevertheless, your task is to arrange the cheapest way to bring all of the jury members to Metrpolis, so that they can work together for k days and then send them back to their home cities. Cost of the arrangement is defined as a total cost of tickets for all used flights. It is allowed for jury member to stay in Metropolis for more than k days.
Input
The first line of input contains three integers n, m and k (1 ≤ n ≤ 105, 0 ≤ m ≤ 105, 1 ≤ k ≤ 106).
The i-th of the following m lines contains the description of the i-th flight defined by four integers di, fi, ti and ci (1 ≤ di ≤ 106, 0 ≤ fi ≤ n, 0 ≤ ti ≤ n, 1 ≤ ci ≤ 106, exactly one of fi and ti equals zero), the day of departure (and arrival), the departure city, the arrival city and the ticket cost.
Output
Output the only integer that is the minimum cost of gathering all jury members in city 0 for k days and then sending them back to their home cities.
If it is impossible to gather everybody in Metropolis for k days and then send them back to their home cities, output "-1" (without the quotes).
Examples
Input
2 6 5
1 1 0 5000
3 2 0 5500
2 2 0 6000
15 0 2 9000
9 0 1 7000
8 0 2 6500
Output
24500
Input
2 4 5
1 2 0 5000
2 1 0 4500
2 1 0 3000
8 0 1 6000
Output
-1
Note
The optimal way to gather everybody in Metropolis in the first sample test is to use flights that take place on days 1, 2, 8 and 9. The only alternative option is to send jury member from second city back home on day 15, that would cost 2500 more.
In the second sample it is impossible to send jury member from city 2 back home from Metropolis. | instruction | 0 | 91,374 | 1 | 182,748 |
Tags: greedy, sortings, two pointers
Correct Solution:
```
g = lambda: map(int, input().split())
n, m, k = g()
F, T = [], []
e = int(3e11)
for i in range(m):
d, f, t, c = g()
if f: F.append((d, f, c))
else: T.append((-d, t, c))
for p in [F, T]:
C = [e] * (n + 1)
s = n * e
q = []
p.sort()
for d, t, c in p:
if C[t] > c:
s += c - C[t]
C[t] = c
if s < e: q.append((s, d))
p.clear()
p += q
s, t = e, (0, 0)
for f in F:
while f:
if t[1] + f[1] + k < 0: s = min(s, f[0] + t[0])
elif T:
t = T.pop()
continue
f = 0
print(s if s < e else -1)
``` | output | 1 | 91,374 | 1 | 182,749 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Country of Metropolia is holding Olympiad of Metrpolises soon. It mean that all jury members of the olympiad should meet together in Metropolis (the capital of the country) for the problem preparation process.
There are n + 1 cities consecutively numbered from 0 to n. City 0 is Metropolis that is the meeting point for all jury members. For each city from 1 to n there is exactly one jury member living there. Olympiad preparation is a long and demanding process that requires k days of work. For all of these k days each of the n jury members should be present in Metropolis to be able to work on problems.
You know the flight schedule in the country (jury members consider themselves important enough to only use flights for transportation). All flights in Metropolia are either going to Metropolis or out of Metropolis. There are no night flights in Metropolia, or in the other words, plane always takes off at the same day it arrives. On his arrival day and departure day jury member is not able to discuss the olympiad. All flights in Megapolia depart and arrive at the same day.
Gather everybody for k days in the capital is a hard objective, doing that while spending the minimum possible money is even harder. Nevertheless, your task is to arrange the cheapest way to bring all of the jury members to Metrpolis, so that they can work together for k days and then send them back to their home cities. Cost of the arrangement is defined as a total cost of tickets for all used flights. It is allowed for jury member to stay in Metropolis for more than k days.
Input
The first line of input contains three integers n, m and k (1 ≤ n ≤ 105, 0 ≤ m ≤ 105, 1 ≤ k ≤ 106).
The i-th of the following m lines contains the description of the i-th flight defined by four integers di, fi, ti and ci (1 ≤ di ≤ 106, 0 ≤ fi ≤ n, 0 ≤ ti ≤ n, 1 ≤ ci ≤ 106, exactly one of fi and ti equals zero), the day of departure (and arrival), the departure city, the arrival city and the ticket cost.
Output
Output the only integer that is the minimum cost of gathering all jury members in city 0 for k days and then sending them back to their home cities.
If it is impossible to gather everybody in Metropolis for k days and then send them back to their home cities, output "-1" (without the quotes).
Examples
Input
2 6 5
1 1 0 5000
3 2 0 5500
2 2 0 6000
15 0 2 9000
9 0 1 7000
8 0 2 6500
Output
24500
Input
2 4 5
1 2 0 5000
2 1 0 4500
2 1 0 3000
8 0 1 6000
Output
-1
Note
The optimal way to gather everybody in Metropolis in the first sample test is to use flights that take place on days 1, 2, 8 and 9. The only alternative option is to send jury member from second city back home on day 15, that would cost 2500 more.
In the second sample it is impossible to send jury member from city 2 back home from Metropolis. | instruction | 0 | 91,375 | 1 | 182,750 |
Tags: greedy, sortings, two pointers
Correct Solution:
```
from bisect import *
from sys import *
n,m,k=[int(i) for i in input().split()]
pln=[]
if m==0:
print(-1)
exit(0)
for i in range(m):
pln.append([int(i) for i in input().split()])
pln.sort()
grp=[[pln[0]]];gt=0;
for i in range(1,m):
if pln[i][0]!=pln[i-1][0]:
gt=gt+1
grp.append([])
grp[gt].append(pln[i])
xx=[]
for i in range(len(grp)):
xx.append(grp[i][0][0])
#print('grp',grp)
#print('xx',xx)
from math import inf
pre=[0]*len(xx)
ct=0
mincost=[inf]*(n+1);sumcost=inf
for i,x in enumerate(grp):
for di,fi,ti,ci in x:
if ti==0:
if mincost[fi]==inf:
ct+=1
if sumcost==inf:
mincost[fi]=min(mincost[fi],ci)
else:
sumcost=sumcost-mincost[fi]
mincost[fi]=min(mincost[fi],ci)
sumcost=sumcost+mincost[fi]
if ct==n and sumcost==inf:
sumcost=sum(mincost[1:])
pre[i]=sumcost
#print(pre)
sa=[0]*len(xx)
ct=0
mincost=[inf]*(n+1);sumcost=inf
grp.reverse()
for i,x in enumerate(grp):
for di,fi,ti,ci in x:
if fi==0:
if mincost[ti]==inf:
ct+=1
if sumcost==inf:
mincost[ti]=min(mincost[ti],ci)
else:
sumcost=sumcost-mincost[ti]
mincost[ti]=min(mincost[ti],ci)
sumcost=sumcost+mincost[ti]
if ct==n and sumcost==inf:
sumcost=sum(mincost[1:])
sa[i]=sumcost
sa.reverse()
#print(sa)
ans=inf
for l,xxi in enumerate(xx):
r=bisect_right(xx,xxi+k)
ansl=pre[l]
ansr= inf if r==len(xx) else sa[r]
ans=min(ans,ansl+ansr)
print(ans) if ans!=inf else print(-1)
``` | output | 1 | 91,375 | 1 | 182,751 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Country of Metropolia is holding Olympiad of Metrpolises soon. It mean that all jury members of the olympiad should meet together in Metropolis (the capital of the country) for the problem preparation process.
There are n + 1 cities consecutively numbered from 0 to n. City 0 is Metropolis that is the meeting point for all jury members. For each city from 1 to n there is exactly one jury member living there. Olympiad preparation is a long and demanding process that requires k days of work. For all of these k days each of the n jury members should be present in Metropolis to be able to work on problems.
You know the flight schedule in the country (jury members consider themselves important enough to only use flights for transportation). All flights in Metropolia are either going to Metropolis or out of Metropolis. There are no night flights in Metropolia, or in the other words, plane always takes off at the same day it arrives. On his arrival day and departure day jury member is not able to discuss the olympiad. All flights in Megapolia depart and arrive at the same day.
Gather everybody for k days in the capital is a hard objective, doing that while spending the minimum possible money is even harder. Nevertheless, your task is to arrange the cheapest way to bring all of the jury members to Metrpolis, so that they can work together for k days and then send them back to their home cities. Cost of the arrangement is defined as a total cost of tickets for all used flights. It is allowed for jury member to stay in Metropolis for more than k days.
Input
The first line of input contains three integers n, m and k (1 ≤ n ≤ 105, 0 ≤ m ≤ 105, 1 ≤ k ≤ 106).
The i-th of the following m lines contains the description of the i-th flight defined by four integers di, fi, ti and ci (1 ≤ di ≤ 106, 0 ≤ fi ≤ n, 0 ≤ ti ≤ n, 1 ≤ ci ≤ 106, exactly one of fi and ti equals zero), the day of departure (and arrival), the departure city, the arrival city and the ticket cost.
Output
Output the only integer that is the minimum cost of gathering all jury members in city 0 for k days and then sending them back to their home cities.
If it is impossible to gather everybody in Metropolis for k days and then send them back to their home cities, output "-1" (without the quotes).
Examples
Input
2 6 5
1 1 0 5000
3 2 0 5500
2 2 0 6000
15 0 2 9000
9 0 1 7000
8 0 2 6500
Output
24500
Input
2 4 5
1 2 0 5000
2 1 0 4500
2 1 0 3000
8 0 1 6000
Output
-1
Note
The optimal way to gather everybody in Metropolis in the first sample test is to use flights that take place on days 1, 2, 8 and 9. The only alternative option is to send jury member from second city back home on day 15, that would cost 2500 more.
In the second sample it is impossible to send jury member from city 2 back home from Metropolis. | instruction | 0 | 91,376 | 1 | 182,752 |
Tags: greedy, sortings, two pointers
Correct Solution:
```
R=lambda :map(int,input().split())
n,m,k=R()
F,T=[],[]
ans=int(1e12)
for i in range(m):
d,f,t,c=R()
if f:F.append((d,f,c))
else:T.append((-d,t,c))
for p in [F,T]:
cost=[ans]*(n+1)
s=n*ans
q=[]
p.sort()
for d,t,c in p:
#print(p)
if c<cost[t]:
#print(c,cost[t])
s+=c-cost[t]
#print(s)
cost[t]=c
if s<ans:
q.append((s,d))
p.clear()
#print(q)
p+=q
#print(p)
s,t=ans,(0,0)
#print(F,T)
for f in F:
while f:
if f[1]+t[1]+k<0:s=min(s,f[0]+t[0])
elif T:
#print(T)
t=T.pop()
#print(T)
# print(t)
continue
#print(f)
f=0
#print(f)
print(s if s<ans else -1)
# Made By Mostafa_Khaled
``` | output | 1 | 91,376 | 1 | 182,753 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Country of Metropolia is holding Olympiad of Metrpolises soon. It mean that all jury members of the olympiad should meet together in Metropolis (the capital of the country) for the problem preparation process.
There are n + 1 cities consecutively numbered from 0 to n. City 0 is Metropolis that is the meeting point for all jury members. For each city from 1 to n there is exactly one jury member living there. Olympiad preparation is a long and demanding process that requires k days of work. For all of these k days each of the n jury members should be present in Metropolis to be able to work on problems.
You know the flight schedule in the country (jury members consider themselves important enough to only use flights for transportation). All flights in Metropolia are either going to Metropolis or out of Metropolis. There are no night flights in Metropolia, or in the other words, plane always takes off at the same day it arrives. On his arrival day and departure day jury member is not able to discuss the olympiad. All flights in Megapolia depart and arrive at the same day.
Gather everybody for k days in the capital is a hard objective, doing that while spending the minimum possible money is even harder. Nevertheless, your task is to arrange the cheapest way to bring all of the jury members to Metrpolis, so that they can work together for k days and then send them back to their home cities. Cost of the arrangement is defined as a total cost of tickets for all used flights. It is allowed for jury member to stay in Metropolis for more than k days.
Input
The first line of input contains three integers n, m and k (1 ≤ n ≤ 105, 0 ≤ m ≤ 105, 1 ≤ k ≤ 106).
The i-th of the following m lines contains the description of the i-th flight defined by four integers di, fi, ti and ci (1 ≤ di ≤ 106, 0 ≤ fi ≤ n, 0 ≤ ti ≤ n, 1 ≤ ci ≤ 106, exactly one of fi and ti equals zero), the day of departure (and arrival), the departure city, the arrival city and the ticket cost.
Output
Output the only integer that is the minimum cost of gathering all jury members in city 0 for k days and then sending them back to their home cities.
If it is impossible to gather everybody in Metropolis for k days and then send them back to their home cities, output "-1" (without the quotes).
Examples
Input
2 6 5
1 1 0 5000
3 2 0 5500
2 2 0 6000
15 0 2 9000
9 0 1 7000
8 0 2 6500
Output
24500
Input
2 4 5
1 2 0 5000
2 1 0 4500
2 1 0 3000
8 0 1 6000
Output
-1
Note
The optimal way to gather everybody in Metropolis in the first sample test is to use flights that take place on days 1, 2, 8 and 9. The only alternative option is to send jury member from second city back home on day 15, that would cost 2500 more.
In the second sample it is impossible to send jury member from city 2 back home from Metropolis.
Submitted Solution:
```
g = lambda: map(int, input().split())
n, m, k = g()
F, T = [], []
e = int(1e9)
for i in range(m):
d, f, t, c = g()
if f: F.append((d, f, c))
else: T.append((-d, t, c))
for p in [F, T]:
C = [e] * (n + 1)
s = n * e
q = []
p.sort()
for d, t, c in p:
if C[t] > c:
s += c - C[t]
C[t] = c
if s < e: q.append((s, d))
p.clear()
p += q
s, t = e, (0, 0)
for f in F:
if t[1] + f[1] + k < 0: s = min(s, f[0] + t[0])
elif T: t = T.pop()
print(s if s < e else -1)
``` | instruction | 0 | 91,377 | 1 | 182,754 |
No | output | 1 | 91,377 | 1 | 182,755 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Country of Metropolia is holding Olympiad of Metrpolises soon. It mean that all jury members of the olympiad should meet together in Metropolis (the capital of the country) for the problem preparation process.
There are n + 1 cities consecutively numbered from 0 to n. City 0 is Metropolis that is the meeting point for all jury members. For each city from 1 to n there is exactly one jury member living there. Olympiad preparation is a long and demanding process that requires k days of work. For all of these k days each of the n jury members should be present in Metropolis to be able to work on problems.
You know the flight schedule in the country (jury members consider themselves important enough to only use flights for transportation). All flights in Metropolia are either going to Metropolis or out of Metropolis. There are no night flights in Metropolia, or in the other words, plane always takes off at the same day it arrives. On his arrival day and departure day jury member is not able to discuss the olympiad. All flights in Megapolia depart and arrive at the same day.
Gather everybody for k days in the capital is a hard objective, doing that while spending the minimum possible money is even harder. Nevertheless, your task is to arrange the cheapest way to bring all of the jury members to Metrpolis, so that they can work together for k days and then send them back to their home cities. Cost of the arrangement is defined as a total cost of tickets for all used flights. It is allowed for jury member to stay in Metropolis for more than k days.
Input
The first line of input contains three integers n, m and k (1 ≤ n ≤ 105, 0 ≤ m ≤ 105, 1 ≤ k ≤ 106).
The i-th of the following m lines contains the description of the i-th flight defined by four integers di, fi, ti and ci (1 ≤ di ≤ 106, 0 ≤ fi ≤ n, 0 ≤ ti ≤ n, 1 ≤ ci ≤ 106, exactly one of fi and ti equals zero), the day of departure (and arrival), the departure city, the arrival city and the ticket cost.
Output
Output the only integer that is the minimum cost of gathering all jury members in city 0 for k days and then sending them back to their home cities.
If it is impossible to gather everybody in Metropolis for k days and then send them back to their home cities, output "-1" (without the quotes).
Examples
Input
2 6 5
1 1 0 5000
3 2 0 5500
2 2 0 6000
15 0 2 9000
9 0 1 7000
8 0 2 6500
Output
24500
Input
2 4 5
1 2 0 5000
2 1 0 4500
2 1 0 3000
8 0 1 6000
Output
-1
Note
The optimal way to gather everybody in Metropolis in the first sample test is to use flights that take place on days 1, 2, 8 and 9. The only alternative option is to send jury member from second city back home on day 15, that would cost 2500 more.
In the second sample it is impossible to send jury member from city 2 back home from Metropolis.
Submitted Solution:
```
g = lambda: map(int, input().split())
n, m, k = g()
F, T = [], []
e = int(2e9)
for i in range(m):
d, f, t, c = g()
if f: F.append((d, f, c))
else: T.append((-d, t, c))
for p in [F, T]:
C = [e] * (n + 1)
s = n * e
q = []
p.sort()
for d, t, c in p:
if C[t] > c:
s += c - C[t]
C[t] = c
if s < e: q.append((s, d))
p.clear()
p += q
s, t = e, (0, 0)
for f in F:
while f:
if t[1] + f[1] + k < 0: s = min(s, f[0] + t[0])
elif T:
t = T.pop()
continue
f = 0
print(s if s < e else -1)
``` | instruction | 0 | 91,378 | 1 | 182,756 |
No | output | 1 | 91,378 | 1 | 182,757 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Country of Metropolia is holding Olympiad of Metrpolises soon. It mean that all jury members of the olympiad should meet together in Metropolis (the capital of the country) for the problem preparation process.
There are n + 1 cities consecutively numbered from 0 to n. City 0 is Metropolis that is the meeting point for all jury members. For each city from 1 to n there is exactly one jury member living there. Olympiad preparation is a long and demanding process that requires k days of work. For all of these k days each of the n jury members should be present in Metropolis to be able to work on problems.
You know the flight schedule in the country (jury members consider themselves important enough to only use flights for transportation). All flights in Metropolia are either going to Metropolis or out of Metropolis. There are no night flights in Metropolia, or in the other words, plane always takes off at the same day it arrives. On his arrival day and departure day jury member is not able to discuss the olympiad. All flights in Megapolia depart and arrive at the same day.
Gather everybody for k days in the capital is a hard objective, doing that while spending the minimum possible money is even harder. Nevertheless, your task is to arrange the cheapest way to bring all of the jury members to Metrpolis, so that they can work together for k days and then send them back to their home cities. Cost of the arrangement is defined as a total cost of tickets for all used flights. It is allowed for jury member to stay in Metropolis for more than k days.
Input
The first line of input contains three integers n, m and k (1 ≤ n ≤ 105, 0 ≤ m ≤ 105, 1 ≤ k ≤ 106).
The i-th of the following m lines contains the description of the i-th flight defined by four integers di, fi, ti and ci (1 ≤ di ≤ 106, 0 ≤ fi ≤ n, 0 ≤ ti ≤ n, 1 ≤ ci ≤ 106, exactly one of fi and ti equals zero), the day of departure (and arrival), the departure city, the arrival city and the ticket cost.
Output
Output the only integer that is the minimum cost of gathering all jury members in city 0 for k days and then sending them back to their home cities.
If it is impossible to gather everybody in Metropolis for k days and then send them back to their home cities, output "-1" (without the quotes).
Examples
Input
2 6 5
1 1 0 5000
3 2 0 5500
2 2 0 6000
15 0 2 9000
9 0 1 7000
8 0 2 6500
Output
24500
Input
2 4 5
1 2 0 5000
2 1 0 4500
2 1 0 3000
8 0 1 6000
Output
-1
Note
The optimal way to gather everybody in Metropolis in the first sample test is to use flights that take place on days 1, 2, 8 and 9. The only alternative option is to send jury member from second city back home on day 15, that would cost 2500 more.
In the second sample it is impossible to send jury member from city 2 back home from Metropolis.
Submitted Solution:
```
g = lambda: map(int, input().split())
n, m, k = g()
F, T = [], []
e = int(1e9)
for i in range(m):
d, f, t, c = g()
if f: F.append((d, f, c))
else: T.append((-d, t, c))
for p in [F, T]:
C = [e] * (n + 1)
s = n * e
q = []
p.sort()
for d, t, c in p:
if C[t] > c:
s += c - C[t]
C[t] = c
if s < e: q.append((s, d))
p.clear()
p += q
f = F.pop()
s = e
for t in T:
while F and t[1] + f[1] + k > 0: f = F.pop()
s = min(s, f[0] + t[0])
print(s if s < e else -1)
``` | instruction | 0 | 91,379 | 1 | 182,758 |
No | output | 1 | 91,379 | 1 | 182,759 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Country of Metropolia is holding Olympiad of Metrpolises soon. It mean that all jury members of the olympiad should meet together in Metropolis (the capital of the country) for the problem preparation process.
There are n + 1 cities consecutively numbered from 0 to n. City 0 is Metropolis that is the meeting point for all jury members. For each city from 1 to n there is exactly one jury member living there. Olympiad preparation is a long and demanding process that requires k days of work. For all of these k days each of the n jury members should be present in Metropolis to be able to work on problems.
You know the flight schedule in the country (jury members consider themselves important enough to only use flights for transportation). All flights in Metropolia are either going to Metropolis or out of Metropolis. There are no night flights in Metropolia, or in the other words, plane always takes off at the same day it arrives. On his arrival day and departure day jury member is not able to discuss the olympiad. All flights in Megapolia depart and arrive at the same day.
Gather everybody for k days in the capital is a hard objective, doing that while spending the minimum possible money is even harder. Nevertheless, your task is to arrange the cheapest way to bring all of the jury members to Metrpolis, so that they can work together for k days and then send them back to their home cities. Cost of the arrangement is defined as a total cost of tickets for all used flights. It is allowed for jury member to stay in Metropolis for more than k days.
Input
The first line of input contains three integers n, m and k (1 ≤ n ≤ 105, 0 ≤ m ≤ 105, 1 ≤ k ≤ 106).
The i-th of the following m lines contains the description of the i-th flight defined by four integers di, fi, ti and ci (1 ≤ di ≤ 106, 0 ≤ fi ≤ n, 0 ≤ ti ≤ n, 1 ≤ ci ≤ 106, exactly one of fi and ti equals zero), the day of departure (and arrival), the departure city, the arrival city and the ticket cost.
Output
Output the only integer that is the minimum cost of gathering all jury members in city 0 for k days and then sending them back to their home cities.
If it is impossible to gather everybody in Metropolis for k days and then send them back to their home cities, output "-1" (without the quotes).
Examples
Input
2 6 5
1 1 0 5000
3 2 0 5500
2 2 0 6000
15 0 2 9000
9 0 1 7000
8 0 2 6500
Output
24500
Input
2 4 5
1 2 0 5000
2 1 0 4500
2 1 0 3000
8 0 1 6000
Output
-1
Note
The optimal way to gather everybody in Metropolis in the first sample test is to use flights that take place on days 1, 2, 8 and 9. The only alternative option is to send jury member from second city back home on day 15, that would cost 2500 more.
In the second sample it is impossible to send jury member from city 2 back home from Metropolis.
Submitted Solution:
```
g = lambda: map(int, input().split())
n, m, k = g()
F, T = [], []
e = int(1e9)
for i in range(m):
d, f, t, c = g()
if f: F.append((d, f, c))
else: T.append((-d, t, c))
for p in [F, T]:
C = [e] * (n + 1)
s = n * e
q = []
p.sort()
for d, t, c in p:
if C[t] > c:
s += c - C[t]
C[t] = c
if s < e: q.append((s, d))
p.clear()
p += q
s, t = e, (0, 0)
for f in F:
while f:
if t[1] + f[1] + k < 0: s = min(s, f[0] + t[0])
elif T:
t = T.pop()
continue
f = 0
print(s if s < e else -1)
``` | instruction | 0 | 91,380 | 1 | 182,760 |
No | output | 1 | 91,380 | 1 | 182,761 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Kuro is living in a country called Uberland, consisting of n towns, numbered from 1 to n, and n - 1 bidirectional roads connecting these towns. It is possible to reach each town from any other. Each road connects two towns a and b. Kuro loves walking and he is planning to take a walking marathon, in which he will choose a pair of towns (u, v) (u ≠ v) and walk from u using the shortest path to v (note that (u, v) is considered to be different from (v, u)).
Oddly, there are 2 special towns in Uberland named Flowrisa (denoted with the index x) and Beetopia (denoted with the index y). Flowrisa is a town where there are many strong-scent flowers, and Beetopia is another town where many bees live. In particular, Kuro will avoid any pair of towns (u, v) if on the path from u to v, he reaches Beetopia after he reached Flowrisa, since the bees will be attracted with the flower smell on Kuro’s body and sting him.
Kuro wants to know how many pair of city (u, v) he can take as his route. Since he’s not really bright, he asked you to help him with this problem.
Input
The first line contains three integers n, x and y (1 ≤ n ≤ 3 ⋅ 10^5, 1 ≤ x, y ≤ n, x ≠ y) - the number of towns, index of the town Flowrisa and index of the town Beetopia, respectively.
n - 1 lines follow, each line contains two integers a and b (1 ≤ a, b ≤ n, a ≠ b), describes a road connecting two towns a and b.
It is guaranteed that from each town, we can reach every other town in the city using the given roads. That is, the given map of towns and roads is a tree.
Output
A single integer resembles the number of pair of towns (u, v) that Kuro can use as his walking route.
Examples
Input
3 1 3
1 2
2 3
Output
5
Input
3 1 3
1 2
1 3
Output
4
Note
On the first example, Kuro can choose these pairs:
* (1, 2): his route would be 1 → 2,
* (2, 3): his route would be 2 → 3,
* (3, 2): his route would be 3 → 2,
* (2, 1): his route would be 2 → 1,
* (3, 1): his route would be 3 → 2 → 1.
Kuro can't choose pair (1, 3) since his walking route would be 1 → 2 → 3, in which Kuro visits town 1 (Flowrisa) and then visits town 3 (Beetopia), which is not allowed (note that pair (3, 1) is still allowed because although Kuro visited Flowrisa and Beetopia, he did not visit them in that order).
On the second example, Kuro can choose the following pairs:
* (1, 2): his route would be 1 → 2,
* (2, 1): his route would be 2 → 1,
* (3, 2): his route would be 3 → 1 → 2,
* (3, 1): his route would be 3 → 1. | instruction | 0 | 91,414 | 1 | 182,828 |
Tags: dfs and similar, trees
Correct Solution:
```
#Code by Sounak, IIESTS
#------------------------------warmup----------------------------
import os
import sys
import math
from io import BytesIO, IOBase
from fractions import Fraction
import collections
from itertools import permutations
from collections import defaultdict
from collections import deque
import threading
threading.stack_size(10**8)
sys.setrecursionlimit(300000)
BUFSIZE = 8192
class FastIO(IOBase):
newlines = 0
def __init__(self, file):
self._fd = file.fileno()
self.buffer = BytesIO()
self.writable = "x" in file.mode or "r" not in file.mode
self.write = self.buffer.write if self.writable else None
def read(self):
while True:
b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
if not b:
break
ptr = self.buffer.tell()
self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr)
self.newlines = 0
return self.buffer.read()
def readline(self):
while self.newlines == 0:
b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
self.newlines = b.count(b"\n") + (not b)
ptr = self.buffer.tell()
self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr)
self.newlines -= 1
return self.buffer.readline()
def flush(self):
if self.writable:
os.write(self._fd, self.buffer.getvalue())
self.buffer.truncate(0), self.buffer.seek(0)
class IOWrapper(IOBase):
def __init__(self, file):
self.buffer = FastIO(file)
self.flush = self.buffer.flush
self.writable = self.buffer.writable
self.write = lambda s: self.buffer.write(s.encode("ascii"))
self.read = lambda: self.buffer.read().decode("ascii")
self.readline = lambda: self.buffer.readline().decode("ascii")
sys.stdin, sys.stdout = IOWrapper(sys.stdin), IOWrapper(sys.stdout)
input = lambda: sys.stdin.readline().rstrip("\r\n")
#-------------------game starts now-----------------------------------------------------
n, x, y = list(map(int, input().split()))
edges = [tuple(map(int, input().split())) for _ in range(n-1)]
chk = [False] * (n+1)
cnt = [1] * (n+1)
adj = defaultdict(list)
for u, v in edges:
adj[u].append(v)
adj[v].append(u)
def dfs(y, x, adj):
vis = set()
stk = [y]
stack_order = []
while stk:
u = stk.pop()
vis.add(u)
if u == x:
chk[u] = True
order = []
for v in adj[u]:
if v not in vis:
stk.append(v)
order.append(v)
if order:
stack_order.append((u, order))
while stack_order:
u = stack_order.pop()
for v in u[1]:
cnt[u[0]] += cnt[v]
chk[u[0]] |= chk[v]
dfs(y, x, adj)
res = 0
for i in adj[y]:
if chk[i]:
res = cnt[y] - cnt[i]
break
print(n*(n-1) - (res*cnt[x]))
``` | output | 1 | 91,414 | 1 | 182,829 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Kuro is living in a country called Uberland, consisting of n towns, numbered from 1 to n, and n - 1 bidirectional roads connecting these towns. It is possible to reach each town from any other. Each road connects two towns a and b. Kuro loves walking and he is planning to take a walking marathon, in which he will choose a pair of towns (u, v) (u ≠ v) and walk from u using the shortest path to v (note that (u, v) is considered to be different from (v, u)).
Oddly, there are 2 special towns in Uberland named Flowrisa (denoted with the index x) and Beetopia (denoted with the index y). Flowrisa is a town where there are many strong-scent flowers, and Beetopia is another town where many bees live. In particular, Kuro will avoid any pair of towns (u, v) if on the path from u to v, he reaches Beetopia after he reached Flowrisa, since the bees will be attracted with the flower smell on Kuro’s body and sting him.
Kuro wants to know how many pair of city (u, v) he can take as his route. Since he’s not really bright, he asked you to help him with this problem.
Input
The first line contains three integers n, x and y (1 ≤ n ≤ 3 ⋅ 10^5, 1 ≤ x, y ≤ n, x ≠ y) - the number of towns, index of the town Flowrisa and index of the town Beetopia, respectively.
n - 1 lines follow, each line contains two integers a and b (1 ≤ a, b ≤ n, a ≠ b), describes a road connecting two towns a and b.
It is guaranteed that from each town, we can reach every other town in the city using the given roads. That is, the given map of towns and roads is a tree.
Output
A single integer resembles the number of pair of towns (u, v) that Kuro can use as his walking route.
Examples
Input
3 1 3
1 2
2 3
Output
5
Input
3 1 3
1 2
1 3
Output
4
Note
On the first example, Kuro can choose these pairs:
* (1, 2): his route would be 1 → 2,
* (2, 3): his route would be 2 → 3,
* (3, 2): his route would be 3 → 2,
* (2, 1): his route would be 2 → 1,
* (3, 1): his route would be 3 → 2 → 1.
Kuro can't choose pair (1, 3) since his walking route would be 1 → 2 → 3, in which Kuro visits town 1 (Flowrisa) and then visits town 3 (Beetopia), which is not allowed (note that pair (3, 1) is still allowed because although Kuro visited Flowrisa and Beetopia, he did not visit them in that order).
On the second example, Kuro can choose the following pairs:
* (1, 2): his route would be 1 → 2,
* (2, 1): his route would be 2 → 1,
* (3, 2): his route would be 3 → 1 → 2,
* (3, 1): his route would be 3 → 1. | instruction | 0 | 91,415 | 1 | 182,830 |
Tags: dfs and similar, trees
Correct Solution:
```
def calculate_max_paths(edges, node, dest, par, cnt):
ans = 1
for child in edges.get(node, []):
if child != par:
ans += calculate_max_paths(edges, child, dest, node, cnt)
if dest == node:
cnt[0] = ans
return ans
def main():
from collections import defaultdict
n, flower, bee = list(map(int, input().split()))
edges = defaultdict(list)
for _ in range(n-1):
x, y = list(map(int, input().split()))
edges[x].append(y)
edges[y].append(x)
bees, flowers = [0], [0]
x = calculate_max_paths(edges, flower, bee, par=None, cnt=bees)
y = calculate_max_paths(edges, bee, flower, par=None, cnt=flowers)
print(x*(x-1) - bees[0]*flowers[0])
if __name__=="__main__":
import sys
import threading
sys.setrecursionlimit(10**6)
threading.stack_size(10**8)
t = threading.Thread(target=main)
t.start()
t.join()
``` | output | 1 | 91,415 | 1 | 182,831 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Kuro is living in a country called Uberland, consisting of n towns, numbered from 1 to n, and n - 1 bidirectional roads connecting these towns. It is possible to reach each town from any other. Each road connects two towns a and b. Kuro loves walking and he is planning to take a walking marathon, in which he will choose a pair of towns (u, v) (u ≠ v) and walk from u using the shortest path to v (note that (u, v) is considered to be different from (v, u)).
Oddly, there are 2 special towns in Uberland named Flowrisa (denoted with the index x) and Beetopia (denoted with the index y). Flowrisa is a town where there are many strong-scent flowers, and Beetopia is another town where many bees live. In particular, Kuro will avoid any pair of towns (u, v) if on the path from u to v, he reaches Beetopia after he reached Flowrisa, since the bees will be attracted with the flower smell on Kuro’s body and sting him.
Kuro wants to know how many pair of city (u, v) he can take as his route. Since he’s not really bright, he asked you to help him with this problem.
Input
The first line contains three integers n, x and y (1 ≤ n ≤ 3 ⋅ 10^5, 1 ≤ x, y ≤ n, x ≠ y) - the number of towns, index of the town Flowrisa and index of the town Beetopia, respectively.
n - 1 lines follow, each line contains two integers a and b (1 ≤ a, b ≤ n, a ≠ b), describes a road connecting two towns a and b.
It is guaranteed that from each town, we can reach every other town in the city using the given roads. That is, the given map of towns and roads is a tree.
Output
A single integer resembles the number of pair of towns (u, v) that Kuro can use as his walking route.
Examples
Input
3 1 3
1 2
2 3
Output
5
Input
3 1 3
1 2
1 3
Output
4
Note
On the first example, Kuro can choose these pairs:
* (1, 2): his route would be 1 → 2,
* (2, 3): his route would be 2 → 3,
* (3, 2): his route would be 3 → 2,
* (2, 1): his route would be 2 → 1,
* (3, 1): his route would be 3 → 2 → 1.
Kuro can't choose pair (1, 3) since his walking route would be 1 → 2 → 3, in which Kuro visits town 1 (Flowrisa) and then visits town 3 (Beetopia), which is not allowed (note that pair (3, 1) is still allowed because although Kuro visited Flowrisa and Beetopia, he did not visit them in that order).
On the second example, Kuro can choose the following pairs:
* (1, 2): his route would be 1 → 2,
* (2, 1): his route would be 2 → 1,
* (3, 2): his route would be 3 → 1 → 2,
* (3, 1): his route would be 3 → 1. | instruction | 0 | 91,416 | 1 | 182,832 |
Tags: dfs and similar, trees
Correct Solution:
```
# from debug import debug
import sys; input = sys.stdin.readline
from collections import deque
n, x, y = map(int, input().split())
x-=1; y-=1
graph = [[] for i in range(n)]
for i in range(n-1):
a, b = map(int, input().split())
graph[a-1].append(b-1)
graph[b-1].append(a-1)
parent = [-1]*n
q = deque([x])
while q:
node = q.popleft()
if node == y: break
for i in graph[node]:
if i == parent[node]: continue
parent[i] = node
q.append(i)
node = y
y_ = parent[y]
while parent[node] != x: node = parent[node]
parent = [-1]*n
parent[x] = node
parent[y] = y_
a, b = 0, 0
q = deque([x])
while q:
node = q.popleft()
a+=1
for i in graph[node]:
if i == parent[node]: continue
parent[i] = node
q.append(i)
q = deque([y])
while q:
node = q.popleft()
b+=1
for i in graph[node]:
if i == parent[node]: continue
parent[i] = node
q.append(i)
ans = n*(n-1) - a*b
print(ans)
``` | output | 1 | 91,416 | 1 | 182,833 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Kuro is living in a country called Uberland, consisting of n towns, numbered from 1 to n, and n - 1 bidirectional roads connecting these towns. It is possible to reach each town from any other. Each road connects two towns a and b. Kuro loves walking and he is planning to take a walking marathon, in which he will choose a pair of towns (u, v) (u ≠ v) and walk from u using the shortest path to v (note that (u, v) is considered to be different from (v, u)).
Oddly, there are 2 special towns in Uberland named Flowrisa (denoted with the index x) and Beetopia (denoted with the index y). Flowrisa is a town where there are many strong-scent flowers, and Beetopia is another town where many bees live. In particular, Kuro will avoid any pair of towns (u, v) if on the path from u to v, he reaches Beetopia after he reached Flowrisa, since the bees will be attracted with the flower smell on Kuro’s body and sting him.
Kuro wants to know how many pair of city (u, v) he can take as his route. Since he’s not really bright, he asked you to help him with this problem.
Input
The first line contains three integers n, x and y (1 ≤ n ≤ 3 ⋅ 10^5, 1 ≤ x, y ≤ n, x ≠ y) - the number of towns, index of the town Flowrisa and index of the town Beetopia, respectively.
n - 1 lines follow, each line contains two integers a and b (1 ≤ a, b ≤ n, a ≠ b), describes a road connecting two towns a and b.
It is guaranteed that from each town, we can reach every other town in the city using the given roads. That is, the given map of towns and roads is a tree.
Output
A single integer resembles the number of pair of towns (u, v) that Kuro can use as his walking route.
Examples
Input
3 1 3
1 2
2 3
Output
5
Input
3 1 3
1 2
1 3
Output
4
Note
On the first example, Kuro can choose these pairs:
* (1, 2): his route would be 1 → 2,
* (2, 3): his route would be 2 → 3,
* (3, 2): his route would be 3 → 2,
* (2, 1): his route would be 2 → 1,
* (3, 1): his route would be 3 → 2 → 1.
Kuro can't choose pair (1, 3) since his walking route would be 1 → 2 → 3, in which Kuro visits town 1 (Flowrisa) and then visits town 3 (Beetopia), which is not allowed (note that pair (3, 1) is still allowed because although Kuro visited Flowrisa and Beetopia, he did not visit them in that order).
On the second example, Kuro can choose the following pairs:
* (1, 2): his route would be 1 → 2,
* (2, 1): his route would be 2 → 1,
* (3, 2): his route would be 3 → 1 → 2,
* (3, 1): his route would be 3 → 1. | instruction | 0 | 91,417 | 1 | 182,834 |
Tags: dfs and similar, trees
Correct Solution:
```
from collections import defaultdict
n,x,y = list(map(int,input().split()))
graph = defaultdict(list)
vis = [False for i in range(n+1)]
mat = [False for i in range(n+1)]
subtree = [0 for i in range(n+1)]
for i in range(n-1):
u,v = list(map(int,input().split()))
graph[u].append(v)
graph[v].append(u)
q = []
cur = 0
for v in graph[x]:
if v!=y:
q.append([v,v])
else:
cur = v
vis[x] = 1
while q!=[]:
temp = q.pop()
u,v = temp
vis[u] = True
subtree[v]+=1
for node in graph[u]:
if vis[node]==False:
if node!=y:
q.append([node,v])
else:
cur = v
val = sum(subtree)
val1 = (val+1-subtree[cur])
val2 = n-(sum(subtree)+1)
val = val1*val2
print(n*(n-1)-val)
``` | output | 1 | 91,417 | 1 | 182,835 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Kuro is living in a country called Uberland, consisting of n towns, numbered from 1 to n, and n - 1 bidirectional roads connecting these towns. It is possible to reach each town from any other. Each road connects two towns a and b. Kuro loves walking and he is planning to take a walking marathon, in which he will choose a pair of towns (u, v) (u ≠ v) and walk from u using the shortest path to v (note that (u, v) is considered to be different from (v, u)).
Oddly, there are 2 special towns in Uberland named Flowrisa (denoted with the index x) and Beetopia (denoted with the index y). Flowrisa is a town where there are many strong-scent flowers, and Beetopia is another town where many bees live. In particular, Kuro will avoid any pair of towns (u, v) if on the path from u to v, he reaches Beetopia after he reached Flowrisa, since the bees will be attracted with the flower smell on Kuro’s body and sting him.
Kuro wants to know how many pair of city (u, v) he can take as his route. Since he’s not really bright, he asked you to help him with this problem.
Input
The first line contains three integers n, x and y (1 ≤ n ≤ 3 ⋅ 10^5, 1 ≤ x, y ≤ n, x ≠ y) - the number of towns, index of the town Flowrisa and index of the town Beetopia, respectively.
n - 1 lines follow, each line contains two integers a and b (1 ≤ a, b ≤ n, a ≠ b), describes a road connecting two towns a and b.
It is guaranteed that from each town, we can reach every other town in the city using the given roads. That is, the given map of towns and roads is a tree.
Output
A single integer resembles the number of pair of towns (u, v) that Kuro can use as his walking route.
Examples
Input
3 1 3
1 2
2 3
Output
5
Input
3 1 3
1 2
1 3
Output
4
Note
On the first example, Kuro can choose these pairs:
* (1, 2): his route would be 1 → 2,
* (2, 3): his route would be 2 → 3,
* (3, 2): his route would be 3 → 2,
* (2, 1): his route would be 2 → 1,
* (3, 1): his route would be 3 → 2 → 1.
Kuro can't choose pair (1, 3) since his walking route would be 1 → 2 → 3, in which Kuro visits town 1 (Flowrisa) and then visits town 3 (Beetopia), which is not allowed (note that pair (3, 1) is still allowed because although Kuro visited Flowrisa and Beetopia, he did not visit them in that order).
On the second example, Kuro can choose the following pairs:
* (1, 2): his route would be 1 → 2,
* (2, 1): his route would be 2 → 1,
* (3, 2): his route would be 3 → 1 → 2,
* (3, 1): his route would be 3 → 1. | instruction | 0 | 91,418 | 1 | 182,836 |
Tags: dfs and similar, trees
Correct Solution:
```
import sys
import threading
from collections import defaultdict
n,x,y=list(map(int,input().split()))
adj=defaultdict(list)
for _ in range(n-1):
a,b=list(map(int,input().split()))
adj[a].append(b)
adj[b].append(a)
def fun(node,par,dest,ans):
cnt=1
for ch in adj[node]:
if ch != par:
cnt+=fun(ch,node,dest,ans)
if node==dest:
ans[0]=cnt*ans[0]
return cnt
def main():
ans=[1]
t=fun(x,0,y,ans)
fun(y,0,x,ans)
print(t*(t-1)-ans[0])
if __name__=="__main__":
sys.setrecursionlimit(10**6)
threading.stack_size(10**8)
t = threading.Thread(target=main)
t.start()
t.join()
``` | output | 1 | 91,418 | 1 | 182,837 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Kuro is living in a country called Uberland, consisting of n towns, numbered from 1 to n, and n - 1 bidirectional roads connecting these towns. It is possible to reach each town from any other. Each road connects two towns a and b. Kuro loves walking and he is planning to take a walking marathon, in which he will choose a pair of towns (u, v) (u ≠ v) and walk from u using the shortest path to v (note that (u, v) is considered to be different from (v, u)).
Oddly, there are 2 special towns in Uberland named Flowrisa (denoted with the index x) and Beetopia (denoted with the index y). Flowrisa is a town where there are many strong-scent flowers, and Beetopia is another town where many bees live. In particular, Kuro will avoid any pair of towns (u, v) if on the path from u to v, he reaches Beetopia after he reached Flowrisa, since the bees will be attracted with the flower smell on Kuro’s body and sting him.
Kuro wants to know how many pair of city (u, v) he can take as his route. Since he’s not really bright, he asked you to help him with this problem.
Input
The first line contains three integers n, x and y (1 ≤ n ≤ 3 ⋅ 10^5, 1 ≤ x, y ≤ n, x ≠ y) - the number of towns, index of the town Flowrisa and index of the town Beetopia, respectively.
n - 1 lines follow, each line contains two integers a and b (1 ≤ a, b ≤ n, a ≠ b), describes a road connecting two towns a and b.
It is guaranteed that from each town, we can reach every other town in the city using the given roads. That is, the given map of towns and roads is a tree.
Output
A single integer resembles the number of pair of towns (u, v) that Kuro can use as his walking route.
Examples
Input
3 1 3
1 2
2 3
Output
5
Input
3 1 3
1 2
1 3
Output
4
Note
On the first example, Kuro can choose these pairs:
* (1, 2): his route would be 1 → 2,
* (2, 3): his route would be 2 → 3,
* (3, 2): his route would be 3 → 2,
* (2, 1): his route would be 2 → 1,
* (3, 1): his route would be 3 → 2 → 1.
Kuro can't choose pair (1, 3) since his walking route would be 1 → 2 → 3, in which Kuro visits town 1 (Flowrisa) and then visits town 3 (Beetopia), which is not allowed (note that pair (3, 1) is still allowed because although Kuro visited Flowrisa and Beetopia, he did not visit them in that order).
On the second example, Kuro can choose the following pairs:
* (1, 2): his route would be 1 → 2,
* (2, 1): his route would be 2 → 1,
* (3, 2): his route would be 3 → 1 → 2,
* (3, 1): his route would be 3 → 1. | instruction | 0 | 91,419 | 1 | 182,838 |
Tags: dfs and similar, trees
Correct Solution:
```
from collections import defaultdict
n, x, y = list(map(int, input().split()))
edges = [tuple(map(int, input().split())) for _ in range(n-1)]
chk = [False] * (n+1)
cnt = [1] * (n+1)
adj = defaultdict(list)
for u, v in edges:
adj[u].append(v)
adj[v].append(u)
def dfs(y, x, adj):
vis = set()
stk = [y]
stack_order = []
while stk:
u = stk.pop()
vis.add(u)
if u == x:
chk[u] = True
order = []
for v in adj[u]:
if v not in vis:
stk.append(v)
order.append(v)
if order:
stack_order.append((u, order))
while stack_order:
u = stack_order.pop()
for v in u[1]:
cnt[u[0]] += cnt[v]
chk[u[0]] |= chk[v]
dfs(y, x, adj)
res = 0
for i in adj[y]:
if chk[i]:
res = cnt[y] - cnt[i]
break
print(n*(n-1) - (res*cnt[x]))
``` | output | 1 | 91,419 | 1 | 182,839 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Kuro is living in a country called Uberland, consisting of n towns, numbered from 1 to n, and n - 1 bidirectional roads connecting these towns. It is possible to reach each town from any other. Each road connects two towns a and b. Kuro loves walking and he is planning to take a walking marathon, in which he will choose a pair of towns (u, v) (u ≠ v) and walk from u using the shortest path to v (note that (u, v) is considered to be different from (v, u)).
Oddly, there are 2 special towns in Uberland named Flowrisa (denoted with the index x) and Beetopia (denoted with the index y). Flowrisa is a town where there are many strong-scent flowers, and Beetopia is another town where many bees live. In particular, Kuro will avoid any pair of towns (u, v) if on the path from u to v, he reaches Beetopia after he reached Flowrisa, since the bees will be attracted with the flower smell on Kuro’s body and sting him.
Kuro wants to know how many pair of city (u, v) he can take as his route. Since he’s not really bright, he asked you to help him with this problem.
Input
The first line contains three integers n, x and y (1 ≤ n ≤ 3 ⋅ 10^5, 1 ≤ x, y ≤ n, x ≠ y) - the number of towns, index of the town Flowrisa and index of the town Beetopia, respectively.
n - 1 lines follow, each line contains two integers a and b (1 ≤ a, b ≤ n, a ≠ b), describes a road connecting two towns a and b.
It is guaranteed that from each town, we can reach every other town in the city using the given roads. That is, the given map of towns and roads is a tree.
Output
A single integer resembles the number of pair of towns (u, v) that Kuro can use as his walking route.
Examples
Input
3 1 3
1 2
2 3
Output
5
Input
3 1 3
1 2
1 3
Output
4
Note
On the first example, Kuro can choose these pairs:
* (1, 2): his route would be 1 → 2,
* (2, 3): his route would be 2 → 3,
* (3, 2): his route would be 3 → 2,
* (2, 1): his route would be 2 → 1,
* (3, 1): his route would be 3 → 2 → 1.
Kuro can't choose pair (1, 3) since his walking route would be 1 → 2 → 3, in which Kuro visits town 1 (Flowrisa) and then visits town 3 (Beetopia), which is not allowed (note that pair (3, 1) is still allowed because although Kuro visited Flowrisa and Beetopia, he did not visit them in that order).
On the second example, Kuro can choose the following pairs:
* (1, 2): his route would be 1 → 2,
* (2, 1): his route would be 2 → 1,
* (3, 2): his route would be 3 → 1 → 2,
* (3, 1): his route would be 3 → 1. | instruction | 0 | 91,420 | 1 | 182,840 |
Tags: dfs and similar, trees
Correct Solution:
```
from collections import defaultdict
n, x, y = list(map(int, input().split()))
sub_checks = [False] * (n + 1)
sub_count = [1] * (n + 1)
def dfs(y, x, graph):
visited = set()
s = [y]
stack_order = []
while len(s) != 0:
curr = s.pop()
visited.add(curr)
if curr == x:
sub_checks[curr] = True
order = []
for child in graph[curr]:
if child not in visited:
s.append(child)
order.append(child)
if len(order) != 0:
stack_order.append((curr, order))
while len(stack_order) != 0:
curr = stack_order.pop()
for child in curr[1]:
sub_count[curr[0]] += sub_count[child]
sub_checks[curr[0]] |= sub_checks[child]
graph = defaultdict(list)
for _ in range(n - 1):
edge = list(map(int, input().split()))
graph[edge[0]].append(edge[1])
graph[edge[1]].append(edge[0])
dfs(y, x, graph)
# Note that branch that contains x has a exception, all nodes from y to x should also count as possible paths so we exclude them
# In order to do that we keep track of which nodes belong the branch with x with sub_checks array
exclude = 0
for child in graph[y]:
if sub_checks[child]:
exclude = sub_count[y] - sub_count[child]
break
print(n * (n - 1) - (exclude * sub_count[x]))
``` | output | 1 | 91,420 | 1 | 182,841 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Kuro is living in a country called Uberland, consisting of n towns, numbered from 1 to n, and n - 1 bidirectional roads connecting these towns. It is possible to reach each town from any other. Each road connects two towns a and b. Kuro loves walking and he is planning to take a walking marathon, in which he will choose a pair of towns (u, v) (u ≠ v) and walk from u using the shortest path to v (note that (u, v) is considered to be different from (v, u)).
Oddly, there are 2 special towns in Uberland named Flowrisa (denoted with the index x) and Beetopia (denoted with the index y). Flowrisa is a town where there are many strong-scent flowers, and Beetopia is another town where many bees live. In particular, Kuro will avoid any pair of towns (u, v) if on the path from u to v, he reaches Beetopia after he reached Flowrisa, since the bees will be attracted with the flower smell on Kuro’s body and sting him.
Kuro wants to know how many pair of city (u, v) he can take as his route. Since he’s not really bright, he asked you to help him with this problem.
Input
The first line contains three integers n, x and y (1 ≤ n ≤ 3 ⋅ 10^5, 1 ≤ x, y ≤ n, x ≠ y) - the number of towns, index of the town Flowrisa and index of the town Beetopia, respectively.
n - 1 lines follow, each line contains two integers a and b (1 ≤ a, b ≤ n, a ≠ b), describes a road connecting two towns a and b.
It is guaranteed that from each town, we can reach every other town in the city using the given roads. That is, the given map of towns and roads is a tree.
Output
A single integer resembles the number of pair of towns (u, v) that Kuro can use as his walking route.
Examples
Input
3 1 3
1 2
2 3
Output
5
Input
3 1 3
1 2
1 3
Output
4
Note
On the first example, Kuro can choose these pairs:
* (1, 2): his route would be 1 → 2,
* (2, 3): his route would be 2 → 3,
* (3, 2): his route would be 3 → 2,
* (2, 1): his route would be 2 → 1,
* (3, 1): his route would be 3 → 2 → 1.
Kuro can't choose pair (1, 3) since his walking route would be 1 → 2 → 3, in which Kuro visits town 1 (Flowrisa) and then visits town 3 (Beetopia), which is not allowed (note that pair (3, 1) is still allowed because although Kuro visited Flowrisa and Beetopia, he did not visit them in that order).
On the second example, Kuro can choose the following pairs:
* (1, 2): his route would be 1 → 2,
* (2, 1): his route would be 2 → 1,
* (3, 2): his route would be 3 → 1 → 2,
* (3, 1): his route would be 3 → 1. | instruction | 0 | 91,421 | 1 | 182,842 |
Tags: dfs and similar, trees
Correct Solution:
```
import sys
import threading
from collections import defaultdict
n,x,y = map(int,input().split())
adj = defaultdict(list)
for i in range(1,n):
a,b = map(int,input().split())
adj[a].append(b)
adj[b].append(a)
def dfs(node,par,v,ans):
sum = 1
for i in range(len(adj[node])):
if adj[node][i]!=par:
sum+= dfs(adj[node][i],node,v,ans)
# sum+=1
if node == v:
ans[0] = sum
return sum
def main():
ans1=[0]
dfs(x,0,y,ans1)
ans2 = [0]
dfs(y,0,x,ans2)
print((n*(n-1))-(ans1[0]*ans2[0]))
if __name__ == "__main__":
sys.setrecursionlimit(10**6)
threading.stack_size(10**8)
t = threading.Thread(target=main)
t.start()
t.join()
``` | output | 1 | 91,421 | 1 | 182,843 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Kuro is living in a country called Uberland, consisting of n towns, numbered from 1 to n, and n - 1 bidirectional roads connecting these towns. It is possible to reach each town from any other. Each road connects two towns a and b. Kuro loves walking and he is planning to take a walking marathon, in which he will choose a pair of towns (u, v) (u ≠ v) and walk from u using the shortest path to v (note that (u, v) is considered to be different from (v, u)).
Oddly, there are 2 special towns in Uberland named Flowrisa (denoted with the index x) and Beetopia (denoted with the index y). Flowrisa is a town where there are many strong-scent flowers, and Beetopia is another town where many bees live. In particular, Kuro will avoid any pair of towns (u, v) if on the path from u to v, he reaches Beetopia after he reached Flowrisa, since the bees will be attracted with the flower smell on Kuro’s body and sting him.
Kuro wants to know how many pair of city (u, v) he can take as his route. Since he’s not really bright, he asked you to help him with this problem.
Input
The first line contains three integers n, x and y (1 ≤ n ≤ 3 ⋅ 10^5, 1 ≤ x, y ≤ n, x ≠ y) - the number of towns, index of the town Flowrisa and index of the town Beetopia, respectively.
n - 1 lines follow, each line contains two integers a and b (1 ≤ a, b ≤ n, a ≠ b), describes a road connecting two towns a and b.
It is guaranteed that from each town, we can reach every other town in the city using the given roads. That is, the given map of towns and roads is a tree.
Output
A single integer resembles the number of pair of towns (u, v) that Kuro can use as his walking route.
Examples
Input
3 1 3
1 2
2 3
Output
5
Input
3 1 3
1 2
1 3
Output
4
Note
On the first example, Kuro can choose these pairs:
* (1, 2): his route would be 1 → 2,
* (2, 3): his route would be 2 → 3,
* (3, 2): his route would be 3 → 2,
* (2, 1): his route would be 2 → 1,
* (3, 1): his route would be 3 → 2 → 1.
Kuro can't choose pair (1, 3) since his walking route would be 1 → 2 → 3, in which Kuro visits town 1 (Flowrisa) and then visits town 3 (Beetopia), which is not allowed (note that pair (3, 1) is still allowed because although Kuro visited Flowrisa and Beetopia, he did not visit them in that order).
On the second example, Kuro can choose the following pairs:
* (1, 2): his route would be 1 → 2,
* (2, 1): his route would be 2 → 1,
* (3, 2): his route would be 3 → 1 → 2,
* (3, 1): his route would be 3 → 1.
Submitted Solution:
```
###### ### ####### ####### ## # ##### ### #####
# # # # # # # # # # # # # ###
# # # # # # # # # # # # # ###
###### ######### # # # # # # ######### #
###### ######### # # # # # # ######### #
# # # # # # # # # # #### # # #
# # # # # # # ## # # # # #
###### # # ####### ####### # # ##### # # # #
from __future__ import print_function # for PyPy2
# from itertools import permutations
# from functools import cmp_to_key # for adding custom comparator
# from fractions import Fraction
from collections import *
from sys import stdin
from bisect import *
from heapq import *
from math import *
g = lambda : stdin.readline().strip()
gl = lambda : g().split()
gil = lambda : [int(var) for var in gl()]
gfl = lambda : [float(var) for var in gl()]
gcl = lambda : list(g())
gbs = lambda : [int(var) for var in g()]
rr = lambda x : reversed(range(x))
mod = int(1e9)+7
inf = float("inf")
n, x, y = gil()
adj = [[] for _ in range(n+1)]
for _ in range(1, n):
n1, n2 = gil()
adj[n1].append(n2)
adj[n2].append(n1)
st = [x]
dp = [0]*(n+1)
vis = [0]*(n+1)
while st:
p = st[-1]
if vis[p]:
st.pop()
dp[p] = 1
for c in adj[p]:
dp[p] += dp[c]
else:
vis[p] = 1
for c in adj[p]:
if not vis[c]:st.append(c)
left = dp[y]
st = [y]
dp = [0]*(n+1)
vis = [0]*(n+1)
while st:
p = st[-1]
if vis[p]:
st.pop()
dp[p] = 1
for c in adj[p]:
dp[p] += dp[c]
else:
vis[p] = 1
for c in adj[p]:
if not vis[c]:st.append(c)
ans = n*(n-1)
ans -= left*dp[x]
print(ans)
``` | instruction | 0 | 91,422 | 1 | 182,844 |
Yes | output | 1 | 91,422 | 1 | 182,845 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Kuro is living in a country called Uberland, consisting of n towns, numbered from 1 to n, and n - 1 bidirectional roads connecting these towns. It is possible to reach each town from any other. Each road connects two towns a and b. Kuro loves walking and he is planning to take a walking marathon, in which he will choose a pair of towns (u, v) (u ≠ v) and walk from u using the shortest path to v (note that (u, v) is considered to be different from (v, u)).
Oddly, there are 2 special towns in Uberland named Flowrisa (denoted with the index x) and Beetopia (denoted with the index y). Flowrisa is a town where there are many strong-scent flowers, and Beetopia is another town where many bees live. In particular, Kuro will avoid any pair of towns (u, v) if on the path from u to v, he reaches Beetopia after he reached Flowrisa, since the bees will be attracted with the flower smell on Kuro’s body and sting him.
Kuro wants to know how many pair of city (u, v) he can take as his route. Since he’s not really bright, he asked you to help him with this problem.
Input
The first line contains three integers n, x and y (1 ≤ n ≤ 3 ⋅ 10^5, 1 ≤ x, y ≤ n, x ≠ y) - the number of towns, index of the town Flowrisa and index of the town Beetopia, respectively.
n - 1 lines follow, each line contains two integers a and b (1 ≤ a, b ≤ n, a ≠ b), describes a road connecting two towns a and b.
It is guaranteed that from each town, we can reach every other town in the city using the given roads. That is, the given map of towns and roads is a tree.
Output
A single integer resembles the number of pair of towns (u, v) that Kuro can use as his walking route.
Examples
Input
3 1 3
1 2
2 3
Output
5
Input
3 1 3
1 2
1 3
Output
4
Note
On the first example, Kuro can choose these pairs:
* (1, 2): his route would be 1 → 2,
* (2, 3): his route would be 2 → 3,
* (3, 2): his route would be 3 → 2,
* (2, 1): his route would be 2 → 1,
* (3, 1): his route would be 3 → 2 → 1.
Kuro can't choose pair (1, 3) since his walking route would be 1 → 2 → 3, in which Kuro visits town 1 (Flowrisa) and then visits town 3 (Beetopia), which is not allowed (note that pair (3, 1) is still allowed because although Kuro visited Flowrisa and Beetopia, he did not visit them in that order).
On the second example, Kuro can choose the following pairs:
* (1, 2): his route would be 1 → 2,
* (2, 1): his route would be 2 → 1,
* (3, 2): his route would be 3 → 1 → 2,
* (3, 1): his route would be 3 → 1.
Submitted Solution:
```
import sys
input=sys.stdin.readline
n,x,y=map(int,input().split())
x-=1
y-=1
g=[[] for i in range(n)]
for _ in range(n-1):
u,v=map(int,input().split())
g[u-1].append(v-1)
g[v-1].append(u-1)
q=[x] # rooted from x and find path from x to y
par=[-1]*n
vis=[False]*n
vis[x]=True
while q:
ver=q.pop()
for to in g[ver]:
if not vis[to]:
par[to]=ver
q.append(to)
vis[to]=True
yy=par[y]
tmp=y
while par[tmp]!=x:
tmp=par[tmp]
xx=tmp
g[x].remove(xx)
g[xx].remove(x)
if yy in g[y]:
g[y].remove(yy)
if y in g[yy]:
g[yy].remove(y)
size_x=1 # size of x-rooted tree
size_y=1
q=[x]
vis=[False]*n
vis[x]=True
while q:
ver=q.pop()
for to in g[ver]:
if not vis[to]:
size_x+=1
q.append(to)
vis[to]=True
q=[y]
vis=[False]*n
vis[y]=True
while q:
ver=q.pop()
for to in g[ver]:
if not vis[to]:
size_y+=1
q.append(to)
vis[to]=True
print(n*(n-1)-size_x*size_y)
``` | instruction | 0 | 91,423 | 1 | 182,846 |
Yes | output | 1 | 91,423 | 1 | 182,847 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Kuro is living in a country called Uberland, consisting of n towns, numbered from 1 to n, and n - 1 bidirectional roads connecting these towns. It is possible to reach each town from any other. Each road connects two towns a and b. Kuro loves walking and he is planning to take a walking marathon, in which he will choose a pair of towns (u, v) (u ≠ v) and walk from u using the shortest path to v (note that (u, v) is considered to be different from (v, u)).
Oddly, there are 2 special towns in Uberland named Flowrisa (denoted with the index x) and Beetopia (denoted with the index y). Flowrisa is a town where there are many strong-scent flowers, and Beetopia is another town where many bees live. In particular, Kuro will avoid any pair of towns (u, v) if on the path from u to v, he reaches Beetopia after he reached Flowrisa, since the bees will be attracted with the flower smell on Kuro’s body and sting him.
Kuro wants to know how many pair of city (u, v) he can take as his route. Since he’s not really bright, he asked you to help him with this problem.
Input
The first line contains three integers n, x and y (1 ≤ n ≤ 3 ⋅ 10^5, 1 ≤ x, y ≤ n, x ≠ y) - the number of towns, index of the town Flowrisa and index of the town Beetopia, respectively.
n - 1 lines follow, each line contains two integers a and b (1 ≤ a, b ≤ n, a ≠ b), describes a road connecting two towns a and b.
It is guaranteed that from each town, we can reach every other town in the city using the given roads. That is, the given map of towns and roads is a tree.
Output
A single integer resembles the number of pair of towns (u, v) that Kuro can use as his walking route.
Examples
Input
3 1 3
1 2
2 3
Output
5
Input
3 1 3
1 2
1 3
Output
4
Note
On the first example, Kuro can choose these pairs:
* (1, 2): his route would be 1 → 2,
* (2, 3): his route would be 2 → 3,
* (3, 2): his route would be 3 → 2,
* (2, 1): his route would be 2 → 1,
* (3, 1): his route would be 3 → 2 → 1.
Kuro can't choose pair (1, 3) since his walking route would be 1 → 2 → 3, in which Kuro visits town 1 (Flowrisa) and then visits town 3 (Beetopia), which is not allowed (note that pair (3, 1) is still allowed because although Kuro visited Flowrisa and Beetopia, he did not visit them in that order).
On the second example, Kuro can choose the following pairs:
* (1, 2): his route would be 1 → 2,
* (2, 1): his route would be 2 → 1,
* (3, 2): his route would be 3 → 1 → 2,
* (3, 1): his route would be 3 → 1.
Submitted Solution:
```
from itertools import combinations,permutations
from collections import defaultdict
import math
import sys
import os
graph=defaultdict(list)
def solution(n,flo,bee):
cleverBrute=[0]*(n+1)
visited=[0]*(n+1)
q=[]
cutNode=0
for elem in graph[flo]:
if elem != bee:
q.append([elem, elem])
else:
cutNode=elem
visited[flo]=1
while q:
temp=q.pop()
currentFrom,currentTo=temp[0],temp[1]
visited[currentFrom]=1
cleverBrute[currentTo]+=1
for elem in graph[currentFrom]:
if not visited[elem]:
if elem != bee:
q.append([elem, currentTo])
else:
cutNode=currentTo
"print(cleverBrute)"
"print(sum(cleverBrute),cleverBrute[cutNode])"
return (sum(cleverBrute)+1-cleverBrute[cutNode])*(n-(sum(cleverBrute)+1))
def main():
n,x,y=map(int,input().strip().split())
for _ in range(n-1):
u,v=map(int,input().strip().split())
graph[u].append(v)
graph[v].append(u)
print(n*(n-1)-(solution(n,x,y)))
if __name__ == '__main__':
main()
"""
3 1 3
1 2
2 3
3 1 3
1 2
1 3
"""
``` | instruction | 0 | 91,424 | 1 | 182,848 |
Yes | output | 1 | 91,424 | 1 | 182,849 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Kuro is living in a country called Uberland, consisting of n towns, numbered from 1 to n, and n - 1 bidirectional roads connecting these towns. It is possible to reach each town from any other. Each road connects two towns a and b. Kuro loves walking and he is planning to take a walking marathon, in which he will choose a pair of towns (u, v) (u ≠ v) and walk from u using the shortest path to v (note that (u, v) is considered to be different from (v, u)).
Oddly, there are 2 special towns in Uberland named Flowrisa (denoted with the index x) and Beetopia (denoted with the index y). Flowrisa is a town where there are many strong-scent flowers, and Beetopia is another town where many bees live. In particular, Kuro will avoid any pair of towns (u, v) if on the path from u to v, he reaches Beetopia after he reached Flowrisa, since the bees will be attracted with the flower smell on Kuro’s body and sting him.
Kuro wants to know how many pair of city (u, v) he can take as his route. Since he’s not really bright, he asked you to help him with this problem.
Input
The first line contains three integers n, x and y (1 ≤ n ≤ 3 ⋅ 10^5, 1 ≤ x, y ≤ n, x ≠ y) - the number of towns, index of the town Flowrisa and index of the town Beetopia, respectively.
n - 1 lines follow, each line contains two integers a and b (1 ≤ a, b ≤ n, a ≠ b), describes a road connecting two towns a and b.
It is guaranteed that from each town, we can reach every other town in the city using the given roads. That is, the given map of towns and roads is a tree.
Output
A single integer resembles the number of pair of towns (u, v) that Kuro can use as his walking route.
Examples
Input
3 1 3
1 2
2 3
Output
5
Input
3 1 3
1 2
1 3
Output
4
Note
On the first example, Kuro can choose these pairs:
* (1, 2): his route would be 1 → 2,
* (2, 3): his route would be 2 → 3,
* (3, 2): his route would be 3 → 2,
* (2, 1): his route would be 2 → 1,
* (3, 1): his route would be 3 → 2 → 1.
Kuro can't choose pair (1, 3) since his walking route would be 1 → 2 → 3, in which Kuro visits town 1 (Flowrisa) and then visits town 3 (Beetopia), which is not allowed (note that pair (3, 1) is still allowed because although Kuro visited Flowrisa and Beetopia, he did not visit them in that order).
On the second example, Kuro can choose the following pairs:
* (1, 2): his route would be 1 → 2,
* (2, 1): his route would be 2 → 1,
* (3, 2): his route would be 3 → 1 → 2,
* (3, 1): his route would be 3 → 1.
Submitted Solution:
```
import sys
from collections import deque
def get_roots_direct_children(q,roots_direct_children,visited,edges):
while q:
root = q.popleft()
visited[root] = True
root_direct_children = list()
for vertice in edges[root]:
if not visited[vertice]:
q.appendleft(vertice)
visited[vertice] = True
root_direct_children.append(vertice)
roots_direct_children.append((root,root_direct_children))
def get_cnt(cnt,roots_direct_children):
while roots_direct_children:
cur_tuple = roots_direct_children.pop()
root = cur_tuple[0]
direct_children = cur_tuple[1]
for direct_child in direct_children:
cnt[root] += cnt[direct_child]
def solve():
input = sys.stdin.readline
n,x,y = map(int,input().split())
edges = {vertice:list() for vertice in range(1,n+1)}
for i in range(n-1):
uv = input().split()
u = int(uv[0])
v = int(uv[1])
edges[u].append(v)
edges[v].append(u)
cnt = [1 for _ in range(n+1)]
visited = [False for _ in range(n+1)]
q = deque()
q.append(x)
roots_direct_children = list()
get_roots_direct_children(q,roots_direct_children,visited,edges)
get_cnt(cnt,roots_direct_children)
cnt_y = cnt[y]
q = deque()
q.append(y)
roots_direct_children = list()
cnt = [1 for _ in range(n+1)]
visited = [False for _ in range(n+1)]
get_roots_direct_children(q,roots_direct_children,visited,edges)
get_cnt(cnt,roots_direct_children)
cnt_x = cnt[x]
total = n*(n-1)
not_ok_routes = cnt_x * cnt_y
result = total - not_ok_routes
print(result)
solve()
``` | instruction | 0 | 91,425 | 1 | 182,850 |
Yes | output | 1 | 91,425 | 1 | 182,851 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Kuro is living in a country called Uberland, consisting of n towns, numbered from 1 to n, and n - 1 bidirectional roads connecting these towns. It is possible to reach each town from any other. Each road connects two towns a and b. Kuro loves walking and he is planning to take a walking marathon, in which he will choose a pair of towns (u, v) (u ≠ v) and walk from u using the shortest path to v (note that (u, v) is considered to be different from (v, u)).
Oddly, there are 2 special towns in Uberland named Flowrisa (denoted with the index x) and Beetopia (denoted with the index y). Flowrisa is a town where there are many strong-scent flowers, and Beetopia is another town where many bees live. In particular, Kuro will avoid any pair of towns (u, v) if on the path from u to v, he reaches Beetopia after he reached Flowrisa, since the bees will be attracted with the flower smell on Kuro’s body and sting him.
Kuro wants to know how many pair of city (u, v) he can take as his route. Since he’s not really bright, he asked you to help him with this problem.
Input
The first line contains three integers n, x and y (1 ≤ n ≤ 3 ⋅ 10^5, 1 ≤ x, y ≤ n, x ≠ y) - the number of towns, index of the town Flowrisa and index of the town Beetopia, respectively.
n - 1 lines follow, each line contains two integers a and b (1 ≤ a, b ≤ n, a ≠ b), describes a road connecting two towns a and b.
It is guaranteed that from each town, we can reach every other town in the city using the given roads. That is, the given map of towns and roads is a tree.
Output
A single integer resembles the number of pair of towns (u, v) that Kuro can use as his walking route.
Examples
Input
3 1 3
1 2
2 3
Output
5
Input
3 1 3
1 2
1 3
Output
4
Note
On the first example, Kuro can choose these pairs:
* (1, 2): his route would be 1 → 2,
* (2, 3): his route would be 2 → 3,
* (3, 2): his route would be 3 → 2,
* (2, 1): his route would be 2 → 1,
* (3, 1): his route would be 3 → 2 → 1.
Kuro can't choose pair (1, 3) since his walking route would be 1 → 2 → 3, in which Kuro visits town 1 (Flowrisa) and then visits town 3 (Beetopia), which is not allowed (note that pair (3, 1) is still allowed because although Kuro visited Flowrisa and Beetopia, he did not visit them in that order).
On the second example, Kuro can choose the following pairs:
* (1, 2): his route would be 1 → 2,
* (2, 1): his route would be 2 → 1,
* (3, 2): his route would be 3 → 1 → 2,
* (3, 1): his route would be 3 → 1.
Submitted Solution:
```
from collections import defaultdict
n,x,y=map(int,input().split())
a=[]
b=defaultdict(list)
for i in range(n-1):
u,v=map(int,input().split())
b[u].append(v)
b[v].append(u)
r=0
print(b)
for i in b:
t=len(b[i])
r+=t*(t-1)+2*t
if i==x and y in b[i]:
r-=(t*(t-1)+2*t)
r+=(t-1)*(t-1)+2*(t-1)+1
print(r//2)
``` | instruction | 0 | 91,426 | 1 | 182,852 |
No | output | 1 | 91,426 | 1 | 182,853 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Kuro is living in a country called Uberland, consisting of n towns, numbered from 1 to n, and n - 1 bidirectional roads connecting these towns. It is possible to reach each town from any other. Each road connects two towns a and b. Kuro loves walking and he is planning to take a walking marathon, in which he will choose a pair of towns (u, v) (u ≠ v) and walk from u using the shortest path to v (note that (u, v) is considered to be different from (v, u)).
Oddly, there are 2 special towns in Uberland named Flowrisa (denoted with the index x) and Beetopia (denoted with the index y). Flowrisa is a town where there are many strong-scent flowers, and Beetopia is another town where many bees live. In particular, Kuro will avoid any pair of towns (u, v) if on the path from u to v, he reaches Beetopia after he reached Flowrisa, since the bees will be attracted with the flower smell on Kuro’s body and sting him.
Kuro wants to know how many pair of city (u, v) he can take as his route. Since he’s not really bright, he asked you to help him with this problem.
Input
The first line contains three integers n, x and y (1 ≤ n ≤ 3 ⋅ 10^5, 1 ≤ x, y ≤ n, x ≠ y) - the number of towns, index of the town Flowrisa and index of the town Beetopia, respectively.
n - 1 lines follow, each line contains two integers a and b (1 ≤ a, b ≤ n, a ≠ b), describes a road connecting two towns a and b.
It is guaranteed that from each town, we can reach every other town in the city using the given roads. That is, the given map of towns and roads is a tree.
Output
A single integer resembles the number of pair of towns (u, v) that Kuro can use as his walking route.
Examples
Input
3 1 3
1 2
2 3
Output
5
Input
3 1 3
1 2
1 3
Output
4
Note
On the first example, Kuro can choose these pairs:
* (1, 2): his route would be 1 → 2,
* (2, 3): his route would be 2 → 3,
* (3, 2): his route would be 3 → 2,
* (2, 1): his route would be 2 → 1,
* (3, 1): his route would be 3 → 2 → 1.
Kuro can't choose pair (1, 3) since his walking route would be 1 → 2 → 3, in which Kuro visits town 1 (Flowrisa) and then visits town 3 (Beetopia), which is not allowed (note that pair (3, 1) is still allowed because although Kuro visited Flowrisa and Beetopia, he did not visit them in that order).
On the second example, Kuro can choose the following pairs:
* (1, 2): his route would be 1 → 2,
* (2, 1): his route would be 2 → 1,
* (3, 2): his route would be 3 → 1 → 2,
* (3, 1): his route would be 3 → 1.
Submitted Solution:
```
n, x, y = map(int, input().split())
if n <= 2:
print(0)
else:
import collections
dic = collections.defaultdict(list)
for _ in range(n-1):
a,b = map(int, input().split())
dic[a].append(b)
dic[b].append(b)
end = []
for key, val in dic.items():
if len(val) == 1:
end.append(key)
left, right= 1, 1
visited = [False for _ in range(n)]
visited[left] = visited[right] = True
q = [end.pop()]
while q:
cur = q.pop(0)
if cur == x or cur == y:
break
nex = dic[cur]
for nexx in nex:
if visited[nexx]:
continue
else:
left += 1
q.append(nexx)
visited[nexx] = True
q = [end.pop()]
while q:
cur = q.pop(0)
if cur == x or cur == y:
break
nex = dic[cur]
for nexx in nex:
if visited[nexx]:
continue
else:
right += 1
q.append(nexx)
visited[nexx] = True
print(n*(n-1) - (left*right))
``` | instruction | 0 | 91,427 | 1 | 182,854 |
No | output | 1 | 91,427 | 1 | 182,855 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Kuro is living in a country called Uberland, consisting of n towns, numbered from 1 to n, and n - 1 bidirectional roads connecting these towns. It is possible to reach each town from any other. Each road connects two towns a and b. Kuro loves walking and he is planning to take a walking marathon, in which he will choose a pair of towns (u, v) (u ≠ v) and walk from u using the shortest path to v (note that (u, v) is considered to be different from (v, u)).
Oddly, there are 2 special towns in Uberland named Flowrisa (denoted with the index x) and Beetopia (denoted with the index y). Flowrisa is a town where there are many strong-scent flowers, and Beetopia is another town where many bees live. In particular, Kuro will avoid any pair of towns (u, v) if on the path from u to v, he reaches Beetopia after he reached Flowrisa, since the bees will be attracted with the flower smell on Kuro’s body and sting him.
Kuro wants to know how many pair of city (u, v) he can take as his route. Since he’s not really bright, he asked you to help him with this problem.
Input
The first line contains three integers n, x and y (1 ≤ n ≤ 3 ⋅ 10^5, 1 ≤ x, y ≤ n, x ≠ y) - the number of towns, index of the town Flowrisa and index of the town Beetopia, respectively.
n - 1 lines follow, each line contains two integers a and b (1 ≤ a, b ≤ n, a ≠ b), describes a road connecting two towns a and b.
It is guaranteed that from each town, we can reach every other town in the city using the given roads. That is, the given map of towns and roads is a tree.
Output
A single integer resembles the number of pair of towns (u, v) that Kuro can use as his walking route.
Examples
Input
3 1 3
1 2
2 3
Output
5
Input
3 1 3
1 2
1 3
Output
4
Note
On the first example, Kuro can choose these pairs:
* (1, 2): his route would be 1 → 2,
* (2, 3): his route would be 2 → 3,
* (3, 2): his route would be 3 → 2,
* (2, 1): his route would be 2 → 1,
* (3, 1): his route would be 3 → 2 → 1.
Kuro can't choose pair (1, 3) since his walking route would be 1 → 2 → 3, in which Kuro visits town 1 (Flowrisa) and then visits town 3 (Beetopia), which is not allowed (note that pair (3, 1) is still allowed because although Kuro visited Flowrisa and Beetopia, he did not visit them in that order).
On the second example, Kuro can choose the following pairs:
* (1, 2): his route would be 1 → 2,
* (2, 1): his route would be 2 → 1,
* (3, 2): his route would be 3 → 1 → 2,
* (3, 1): his route would be 3 → 1.
Submitted Solution:
```
n, flower, bee = list(map(int, input().split()))
roads = {}
for _ in range(n-1):
x, y = list(map(int, input().split()))
if x not in roads:
roads[x] = [y]
else:
roads[x].append(y)
if y not in roads:
roads[y] = [x]
else:
roads[y].append(x)
def dfs(bee, flower):
q = []
visited = set()
visited.add(flower)
for y in roads[flower]:
if y == bee:
return flower, 0
q.append([y,1])
while q:
now = q.pop()
visited.add(now[0])
for y in roads[now[0]]:
if y not in visited:
if y == bee:
return now
q.append([y, now[1]+1])
def total(bee, ban):
q = []
visited = set()
visited.add(bee)
count = 0
for y in roads[bee]:
if y == ban:
continue
q.append(y)
while q:
now = q.pop()
count += 1
visited.add(now)
for y in roads[now]:
if y not in visited:
q.append(y)
return count
# def final(here):
# q = []
# visited = set()
# visited.add(here)
# for y in roads[here]:
# q.append([y,1])
# total = 0
# while q:
# now = q.pop()
# total += now[1]*2
# visited.add(now[0])
# for y in roads[now[0]]:
# if y not in visited:
# q.append([y,now[1]+1])
# return total
# for i in roads.items():
# print(i, i[0])
# if len(i[1]) == 1:
# n_total = final(i[0])
# break
ban,road = dfs(bee, flower)
minus = total(bee,ban)+1
print(n*(n-1)-(n-road-minus)*minus)
``` | instruction | 0 | 91,428 | 1 | 182,856 |
No | output | 1 | 91,428 | 1 | 182,857 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Kuro is living in a country called Uberland, consisting of n towns, numbered from 1 to n, and n - 1 bidirectional roads connecting these towns. It is possible to reach each town from any other. Each road connects two towns a and b. Kuro loves walking and he is planning to take a walking marathon, in which he will choose a pair of towns (u, v) (u ≠ v) and walk from u using the shortest path to v (note that (u, v) is considered to be different from (v, u)).
Oddly, there are 2 special towns in Uberland named Flowrisa (denoted with the index x) and Beetopia (denoted with the index y). Flowrisa is a town where there are many strong-scent flowers, and Beetopia is another town where many bees live. In particular, Kuro will avoid any pair of towns (u, v) if on the path from u to v, he reaches Beetopia after he reached Flowrisa, since the bees will be attracted with the flower smell on Kuro’s body and sting him.
Kuro wants to know how many pair of city (u, v) he can take as his route. Since he’s not really bright, he asked you to help him with this problem.
Input
The first line contains three integers n, x and y (1 ≤ n ≤ 3 ⋅ 10^5, 1 ≤ x, y ≤ n, x ≠ y) - the number of towns, index of the town Flowrisa and index of the town Beetopia, respectively.
n - 1 lines follow, each line contains two integers a and b (1 ≤ a, b ≤ n, a ≠ b), describes a road connecting two towns a and b.
It is guaranteed that from each town, we can reach every other town in the city using the given roads. That is, the given map of towns and roads is a tree.
Output
A single integer resembles the number of pair of towns (u, v) that Kuro can use as his walking route.
Examples
Input
3 1 3
1 2
2 3
Output
5
Input
3 1 3
1 2
1 3
Output
4
Note
On the first example, Kuro can choose these pairs:
* (1, 2): his route would be 1 → 2,
* (2, 3): his route would be 2 → 3,
* (3, 2): his route would be 3 → 2,
* (2, 1): his route would be 2 → 1,
* (3, 1): his route would be 3 → 2 → 1.
Kuro can't choose pair (1, 3) since his walking route would be 1 → 2 → 3, in which Kuro visits town 1 (Flowrisa) and then visits town 3 (Beetopia), which is not allowed (note that pair (3, 1) is still allowed because although Kuro visited Flowrisa and Beetopia, he did not visit them in that order).
On the second example, Kuro can choose the following pairs:
* (1, 2): his route would be 1 → 2,
* (2, 1): his route would be 2 → 1,
* (3, 2): his route would be 3 → 1 → 2,
* (3, 1): his route would be 3 → 1.
Submitted Solution:
```
import io, os
input = io.BytesIO(os.read(0,os.fstat(0).st_size)).readline
n, x, y = map(int, input().split())
adj = [[] for i in range(n+1)]
for i in range(n-1):
u, v = map(int, input().split())
adj[u].append(v)
adj[v].append(u)
v = [0]*(n+1)
q = [[x, []]]
edge = []
while q:
e, l = q.pop()
if not v[e]:
l.append(e)
v[e] = 1
if e == y:
edge = l
break
for i in adj[e]:
if not v[i]:
q.append((i, l))
q = [x]
x_cmp = 0
y_cmp = 0
v = [0]*(n+1)
while q:
e = q.pop()
if not v[e]:
x_cmp += 1
v[e] = 1
for j in adj[e]:
if not v[j] and (e != x or j != edge[1]):
q.append(j)
q = [y]
while q:
e = q.pop()
if not v[e]:
y_cmp += 1
v[e] = 1
for j in adj[e]:
if not v[j] and (e != y or j != edge[-2]):
q.append(j)
print((n*(n-1))-(x_cmp*y_cmp))
``` | instruction | 0 | 91,429 | 1 | 182,858 |
No | output | 1 | 91,429 | 1 | 182,859 |
Provide a correct Python 3 solution for this coding contest problem.
There are N towns numbered 1, 2, \cdots, N.
Some roads are planned to be built so that each of them connects two distinct towns bidirectionally. Currently, there are no roads connecting towns.
In the planning of construction, each town chooses one town different from itself and requests the following: roads are built so that the chosen town is reachable from itself using one or more roads.
These requests from the towns are represented by an array P_1, P_2, \cdots, P_N. If P_i = -1, it means that Town i has not chosen the request; if 1 \leq P_i \leq N, it means that Town i has chosen Town P_i.
Let K be the number of towns i such that P_i = -1. There are (N-1)^K ways in which the towns can make the requests. For each way to make requests, find the minimum number of roads needed to meet all the requests, and print the sum of those (N-1)^K numbers, modulo (10^9+7).
Constraints
* 2 \leq N \leq 5000
* P_i = -1 or 1 \leq P_i \leq N.
* P_i \neq i
* All values in input are integers.
Input
Input is given from Standard Input in the following format:
N
P_1 P_2 \cdots P_N
Output
For each way to make requests, find the minimum number of roads needed to meet all the requests, and print the sum of those (N-1)^K numbers, modulo (10^9+7).
Examples
Input
4
2 1 -1 3
Output
8
Input
2
2 1
Output
1
Input
10
2 6 9 -1 6 9 -1 -1 -1 -1
Output
527841 | instruction | 0 | 91,462 | 1 | 182,924 |
"Correct Solution:
```
#!/usr/bin/env python3
import sys
sys.setrecursionlimit(10**8)
INF = float("inf")
MOD = 1000000007 # type: int
class UnionFind():
def __init__(self, n):
self.n = n
self.parents = [-1] * n
def find(self, x):
if self.parents[x] < 0:
return x
else:
self.parents[x] = self.find(self.parents[x])
return self.parents[x]
def union(self, x, y):
x = self.find(x)
y = self.find(y)
if x == y:
return
if self.parents[x] > self.parents[y]:
x, y = y, x
self.parents[x] += self.parents[y]
self.parents[y] = x
def size(self, x):
return -self.parents[self.find(x)]
def same(self, x, y):
return self.find(x) == self.find(y)
def members(self, x):
root = self.find(x)
return [i for i in range(self.n) if self.find(i) == root]
def roots(self):
return [i for i, x in enumerate(self.parents) if x < 0]
def group_count(self):
return len(self.roots())
def all_group_members(self):
return {r: self.members(r) for r in self.roots()}
def __str__(self):
return '\n'.join('{}: {}'.format(r, self.members(r)) for r in self.roots())
def main():
N = int(input())
P = list(map(int, input().split()))
# 確定している道でグルーピングする
uf = UnionFind(N)
K = 0
for i, p in enumerate(P):
if p != -1:
uf.union(i, p-1)
else:
K += 1
# 階乗の事前計算
factorial = [1]*K
for i in range(K-1):
factorial[i+1] = ((i+1)*factorial[i]) % MOD
# 要請が未完のノードが属するグループサイズをメモ
size_undef = [0]*K
curr = 0
for i, p in enumerate(P):
if p == -1:
size_undef[curr] = uf.size(i)
curr += 1
# dp[i, j]: i個の根付き木を見てj個を選んだ時の\sum{\prod_v S_v}
# 「メモリ削減したdpとN^2確保するDP、どっちが早いんやろなあ」
dp = [0]*(K+1)
dp[0] = 1
dp_new = dp[:]
for i in range(1, K+1):
for j in range(i):
dp_new[j+1] += dp[j]*size_undef[i-1]
dp = dp_new[:]
# ただしj=1個を選んだ時のものは特別にsize[i]-1を考える必要がある
if K >= 1:
tot = 0
for s in size_undef:
tot += s-1
dp[1] = tot
# cycleをカウントする
cycle_count = 0
for i in range(1, K+1):
# i個のグループからなるサイクルがひとつできる
cycle_count += dp[i]*factorial[i-1]*pow(N-1, K-i, MOD)
cycle_count %= MOD
# すでに固定サイクルがあれば数える
cycle_count += (uf.group_count()-K)*pow(N-1, K, MOD)
# 求めます
ans = N*pow(N-1, K, MOD) - cycle_count
ans %= MOD
print(ans)
return
if __name__ == '__main__':
main()
``` | output | 1 | 91,462 | 1 | 182,925 |
Provide a correct Python 3 solution for this coding contest problem.
There are N towns numbered 1, 2, \cdots, N.
Some roads are planned to be built so that each of them connects two distinct towns bidirectionally. Currently, there are no roads connecting towns.
In the planning of construction, each town chooses one town different from itself and requests the following: roads are built so that the chosen town is reachable from itself using one or more roads.
These requests from the towns are represented by an array P_1, P_2, \cdots, P_N. If P_i = -1, it means that Town i has not chosen the request; if 1 \leq P_i \leq N, it means that Town i has chosen Town P_i.
Let K be the number of towns i such that P_i = -1. There are (N-1)^K ways in which the towns can make the requests. For each way to make requests, find the minimum number of roads needed to meet all the requests, and print the sum of those (N-1)^K numbers, modulo (10^9+7).
Constraints
* 2 \leq N \leq 5000
* P_i = -1 or 1 \leq P_i \leq N.
* P_i \neq i
* All values in input are integers.
Input
Input is given from Standard Input in the following format:
N
P_1 P_2 \cdots P_N
Output
For each way to make requests, find the minimum number of roads needed to meet all the requests, and print the sum of those (N-1)^K numbers, modulo (10^9+7).
Examples
Input
4
2 1 -1 3
Output
8
Input
2
2 1
Output
1
Input
10
2 6 9 -1 6 9 -1 -1 -1 -1
Output
527841 | instruction | 0 | 91,463 | 1 | 182,926 |
"Correct Solution:
```
def productall(a):
N = len(a)
if N == 0: return [1]
A = [1] * N + a[:]
P = 10 ** 9 + 7
k = 12
K = k * 8
pa1 = (1 << k * 4 + 16) - ((1 << k * 4 + 16) % P)
pa2 = (1 << k * 2 + 24) - ((1 << k * 2 + 24) % P)
pa3 = (1 << k + 28) - ((1 << k + 28) % P)
m1 = int(("1" * (k * 4 - 16) + "0" * (k * 4 + 16)) * 5050, 2)
m2 = int(("1" * (k * 6 - 24) + "0" * (k * 2 + 24)) * 5050, 2)
m3 = int(("1" * (k * 7 - 28) + "0" * (k + 28)) * 5050, 2)
def modP(x):
x -= ((x & m1) >> k * 4 + 16) * pa1
x -= ((x & m2) >> k * 2 + 24) * pa2
x -= ((x & m3) >> k + 28) * pa3
return x
for i in range(N)[::-1]:
A[i] = modP(A[2*i] * A[2*i+1])
t = bin(A[1])[2:] + "_"
return [int(t[-(i+1) * K - 1:-i * K - 1], 2) % P for i in range((len(t)+K-2) // K)]
def par(a):
L = []
while P[a] != a:
L.append(a)
a = P[a]
for l in L:
P[l] = a
return a
def unite(a, b):
pa = par(a)
pb = par(b)
if pa == pb: return
if LEN[pa] < LEN[pb]:
a, b, pa, pb = b, a, pb, pa
P[pb] = pa
if LEN[pa] == LEN[pb]: LEN[pa] += 1
CNT[pa] += CNT[pb]
def cnt(a):
return CNT[par(a)]
N = int(input())
P = [i for i in range(N)]
LEN = [1] * N
CNT = [1] * N
FULL = [0] * N
A = [int(a) - 1 for a in input().split()]
for i, a in enumerate(A):
if a < 0: continue
if par(i) != par(a):
unite(i, a)
else:
FULL[i] = 1
for i in range(N):
if FULL[i]:
FULL[par(i)] = 1
X = []
Y = []
for i in range(N):
if par(i) == i:
if FULL[i] == 0:
X.append(CNT[i])
else:
Y.append(CNT[i])
M = len(X)
mod = 10 ** 9 + 7
ans = (sum(X) + sum(Y) - len(Y)) * pow(N - 1, M, mod) % mod
L = productall([(a << 96) + 1 for a in X])
if M:
fa = 1
ans = (ans + M * pow(N - 1, M - 1, mod)) % mod
for i, l in enumerate(L):
if i == 0: continue
ans = (ans - l * fa * pow(N - 1, M - i, mod)) % mod
fa = fa * i % mod
print(ans)
``` | output | 1 | 91,463 | 1 | 182,927 |
Provide a correct Python 3 solution for this coding contest problem.
There are N towns numbered 1, 2, \cdots, N.
Some roads are planned to be built so that each of them connects two distinct towns bidirectionally. Currently, there are no roads connecting towns.
In the planning of construction, each town chooses one town different from itself and requests the following: roads are built so that the chosen town is reachable from itself using one or more roads.
These requests from the towns are represented by an array P_1, P_2, \cdots, P_N. If P_i = -1, it means that Town i has not chosen the request; if 1 \leq P_i \leq N, it means that Town i has chosen Town P_i.
Let K be the number of towns i such that P_i = -1. There are (N-1)^K ways in which the towns can make the requests. For each way to make requests, find the minimum number of roads needed to meet all the requests, and print the sum of those (N-1)^K numbers, modulo (10^9+7).
Constraints
* 2 \leq N \leq 5000
* P_i = -1 or 1 \leq P_i \leq N.
* P_i \neq i
* All values in input are integers.
Input
Input is given from Standard Input in the following format:
N
P_1 P_2 \cdots P_N
Output
For each way to make requests, find the minimum number of roads needed to meet all the requests, and print the sum of those (N-1)^K numbers, modulo (10^9+7).
Examples
Input
4
2 1 -1 3
Output
8
Input
2
2 1
Output
1
Input
10
2 6 9 -1 6 9 -1 -1 -1 -1
Output
527841 | instruction | 0 | 91,464 | 1 | 182,928 |
"Correct Solution:
```
def modfac(n, MOD):
f = 1
factorials = [1]
for m in range(1, n + 1):
f *= m
f %= MOD
factorials.append(f)
inv = pow(f, MOD - 2, MOD)
invs = [1] * (n + 1)
invs[n] = inv
for m in range(n, 1, -1):
inv *= m
inv %= MOD
invs[m - 1] = inv
return factorials, invs
def modnCr(n,r,mod,fac,inv): #上で求めたfacとinvsを引数に入れるべし(上の関数で与えたnが計算できる最大のnになる)
return fac[n] * inv[n-r] * inv[r] % mod
def uf_find(n,p):
ufl = []
while p[n] != n:
ufl.append(n)
n = p[n]
for i in ufl:
p[i] = n
return n
def uf_union(a,b,p,rank,tsize):
ap = uf_find(a,p)
bp = uf_find(b,p)
if ap == bp:
return True
else:
if rank[ap] > rank[bp]:
p[bp] = ap
tsize[ap] += tsize[bp]
elif rank[ap] < rank[bp]:
p[ap] = bp
tsize[bp] += tsize[ap]
else:
p[bp] = ap
rank[ap] += 1
tsize[ap] += tsize[bp]
return False
mod = 10**9+7
N = int(input())
P = list(map(int,input().split()))
fac,inv = modfac(N+10,mod)
ans = 0
p = [i for i in range(N)]
rank = [1] * N
tsize = [1] * N
for i in range(N):
if P[i] == -1:
continue
nex = P[i] - 1
uf_union(i,nex,p,rank,tsize)
able = [True] * N
c = []
d = []
for i in range(N):
if P[i] == -1:
nowp = uf_find(i,p)
c.append(tsize[nowp])
able[nowp] = False
for i in range(N):
if uf_find(i,p) == i and able[i]:
d.append(tsize[i])
ans = 0
for i in c:
ans += i
for i in d:
ans += i-1
ans *= pow(N-1,len(c),mod)
ans %= mod
#print (ans)
#自分を選んで減る場合
for i in c:
ans -= (i-1) * pow(N-1,len(c)-1,mod)
ans %= mod
#互いに選んで減る場合
dp = [0] * (len(c)+1)
dp[0] = 1
for i in c:
for j in range(len(c)-1,-1,-1):
dp[j+1] += dp[j] * i
#dp[j+1] %= mod
#print (c,dp)
for i in range(2,len(c)+1):
ans -= dp[i] * fac[i-1] * pow(N-1,len(c)-i,mod)
ans %= mod
print (ans % mod)
"""
連結成分で考える
全ての街が -1 以外を選んだ時、
最小数 + -1の数
-1同士が選ぶことを考える
-1同士が選んだ時のみ答えが1減る
そうでなければ変化なし?
連結成分に-1は1つ以下しかない?
→正しい
-1を含まない連結成分は分けておく
-1の連結成分同士が求め合えば、答えは-1される
a個含む & bこ含む
場合
a*b * (N-1)^(K-2)
引けばいい
自分の連結成分を求めるときも1減る
ループを作ると1減るんだ!
"""
``` | output | 1 | 91,464 | 1 | 182,929 |
Provide a correct Python 3 solution for this coding contest problem.
There are N towns numbered 1, 2, \cdots, N.
Some roads are planned to be built so that each of them connects two distinct towns bidirectionally. Currently, there are no roads connecting towns.
In the planning of construction, each town chooses one town different from itself and requests the following: roads are built so that the chosen town is reachable from itself using one or more roads.
These requests from the towns are represented by an array P_1, P_2, \cdots, P_N. If P_i = -1, it means that Town i has not chosen the request; if 1 \leq P_i \leq N, it means that Town i has chosen Town P_i.
Let K be the number of towns i such that P_i = -1. There are (N-1)^K ways in which the towns can make the requests. For each way to make requests, find the minimum number of roads needed to meet all the requests, and print the sum of those (N-1)^K numbers, modulo (10^9+7).
Constraints
* 2 \leq N \leq 5000
* P_i = -1 or 1 \leq P_i \leq N.
* P_i \neq i
* All values in input are integers.
Input
Input is given from Standard Input in the following format:
N
P_1 P_2 \cdots P_N
Output
For each way to make requests, find the minimum number of roads needed to meet all the requests, and print the sum of those (N-1)^K numbers, modulo (10^9+7).
Examples
Input
4
2 1 -1 3
Output
8
Input
2
2 1
Output
1
Input
10
2 6 9 -1 6 9 -1 -1 -1 -1
Output
527841 | instruction | 0 | 91,465 | 1 | 182,930 |
"Correct Solution:
```
from collections import defaultdict, deque, Counter
from heapq import heappush, heappop, heapify
import math
import bisect
import random
from itertools import permutations, accumulate, combinations, product
import sys
import string
from bisect import bisect_left, bisect_right
from math import factorial, ceil, floor, cos, radians, pi, sin
from operator import mul
from functools import reduce
from operator import mul
mod = 10 ** 9 + 7
sys.setrecursionlimit(2147483647)
INF = 10 ** 13
def LI(): return list(map(int, sys.stdin.buffer.readline().split()))
def I(): return int(sys.stdin.buffer.readline())
def LS(): return sys.stdin.buffer.readline().rstrip().decode('utf-8').split()
def S(): return sys.stdin.buffer.readline().rstrip().decode('utf-8')
def IR(n): return [I() for i in range(n)]
def LIR(n): return [LI() for i in range(n)]
def SR(n): return [S() for i in range(n)]
def LSR(n): return [LS() for i in range(n)]
def SRL(n): return [list(S()) for i in range(n)]
def MSRL(n): return [[int(j) for j in list(S())] for i in range(n)]
class UnionFind():
def __init__(self, n):
self.n = n
self.parents = [-1] * n
def find(self, x):
if self.parents[x] < 0:
return x
else:
self.parents[x] = self.find(self.parents[x])
return self.parents[x]
def union(self, x, y):
x = self.find(x)
y = self.find(y)
if x == y:
return
if self.parents[x] > self.parents[y]:
x, y = y, x
self.parents[x] += self.parents[y]
self.parents[y] = x
def size(self, x):
return -self.parents[self.find(x)]
def same(self, x, y):
return self.find(x) == self.find(y)
def members(self, x):
root = self.find(x)
return [i for i in range(self.n) if self.find(i) == root]
def roots(self):
return [i for i, x in enumerate(self.parents) if x < 0]
def group_count(self):
return len(self.roots())
def all_group_members(self):
return {r: self.members(r) for r in self.roots()}
n = I()
P = LI()
fac = [1] * (n + 1)
inv = [1] * (n + 1)
for j in range(1, n + 1):
fac[j] = fac[j-1] * j % mod
inv[n] = pow(fac[n], mod-2, mod)
for j in range(n-1, -1, -1):
inv[j] = inv[j+1] * (j+1) % mod
def comb(n, r):
if r > n or n < 0 or r < 0:
return 0
return fac[n] * inv[n - r] * inv[r] % mod
ret = 0
for p in P:
if p == -1:
ret += 1
U = UnionFind(n)
for i in range(n):
if P[i] != -1:
U.union(P[i] - 1, i)
L = []
for j in range(n):
if P[j] == -1:
L += [U.size(j)]
dp = [0] * (len(L) + 1)
dp[0] = 1
for l in range(1, len(L) + 1):
for m in range(l, 0, -1):
dp[m] += dp[m - 1] * L[l - 1]
if L:
dp[1] = sum(L) - len(L)
cycle_cnt = 0
for i in range(1, len(L) + 1):
cycle_cnt = (cycle_cnt + fac[i - 1] * dp[i] * pow(n - 1, len(L) - i, mod)) % mod
ans = (n - (U.group_count() - ret)) * pow(n - 1, ret, mod) % mod
print((ans - cycle_cnt) % mod)
``` | output | 1 | 91,465 | 1 | 182,931 |
Provide a correct Python 3 solution for this coding contest problem.
There are N towns numbered 1, 2, \cdots, N.
Some roads are planned to be built so that each of them connects two distinct towns bidirectionally. Currently, there are no roads connecting towns.
In the planning of construction, each town chooses one town different from itself and requests the following: roads are built so that the chosen town is reachable from itself using one or more roads.
These requests from the towns are represented by an array P_1, P_2, \cdots, P_N. If P_i = -1, it means that Town i has not chosen the request; if 1 \leq P_i \leq N, it means that Town i has chosen Town P_i.
Let K be the number of towns i such that P_i = -1. There are (N-1)^K ways in which the towns can make the requests. For each way to make requests, find the minimum number of roads needed to meet all the requests, and print the sum of those (N-1)^K numbers, modulo (10^9+7).
Constraints
* 2 \leq N \leq 5000
* P_i = -1 or 1 \leq P_i \leq N.
* P_i \neq i
* All values in input are integers.
Input
Input is given from Standard Input in the following format:
N
P_1 P_2 \cdots P_N
Output
For each way to make requests, find the minimum number of roads needed to meet all the requests, and print the sum of those (N-1)^K numbers, modulo (10^9+7).
Examples
Input
4
2 1 -1 3
Output
8
Input
2
2 1
Output
1
Input
10
2 6 9 -1 6 9 -1 -1 -1 -1
Output
527841 | instruction | 0 | 91,466 | 1 | 182,932 |
"Correct Solution:
```
from collections import defaultdict, deque, Counter
from heapq import heappush, heappop, heapify
import math
import bisect
import random
from itertools import permutations, accumulate, combinations, product
import sys
import string
from bisect import bisect_left, bisect_right
from math import factorial, ceil, floor, cos, radians, pi, sin
from operator import mul
from functools import reduce
from operator import mul
mod = 10 ** 9 + 7
sys.setrecursionlimit(2147483647)
INF = 10 ** 13
def LI(): return list(map(int, sys.stdin.buffer.readline().split()))
def I(): return int(sys.stdin.buffer.readline())
def LS(): return sys.stdin.buffer.readline().rstrip().decode('utf-8').split()
def S(): return sys.stdin.buffer.readline().rstrip().decode('utf-8')
def IR(n): return [I() for i in range(n)]
def LIR(n): return [LI() for i in range(n)]
def SR(n): return [S() for i in range(n)]
def LSR(n): return [LS() for i in range(n)]
def SRL(n): return [list(S()) for i in range(n)]
def MSRL(n): return [[int(j) for j in list(S())] for i in range(n)]
class UnionFind:
def __init__(self, n):
# 負 : 根であることを示す。絶対値はランクを示す
# 非負: 根でないことを示す。値は親を示す
self.table = [-1] * n
self.size = [1] * n
self.group_num = n
def root(self, x):
if self.table[x] < 0:
return x
else:
self.table[x] = self.root(self.table[x])
return self.table[x]
def get_size(self, x):
r = self.root(x)
return self.size[r]
def is_same(self, x, y):
return self.root(x) == self.root(y)
def union(self, x, y):
r1 = self.root(x)
r2 = self.root(y)
if r1 == r2:
return
# ランクの取得
d1 = self.table[r1]
d2 = self.table[r2]
if d1 <= d2:
self.table[r2] = r1
self.size[r1] += self.size[r2]
else:
self.table[r1] = r2
self.size[r2] += self.size[r1]
self.group_num -= 1
n = I()
P = LI()
fac = [1] * (n + 1)
inv = [1] * (n + 1)
for j in range(1, n + 1):
fac[j] = fac[j-1] * j % mod
inv[n] = pow(fac[n], mod-2, mod)
for j in range(n-1, -1, -1):
inv[j] = inv[j+1] * (j+1) % mod
def comb(n, r):
if r > n or n < 0 or r < 0:
return 0
return fac[n] * inv[n - r] * inv[r] % mod
ret = 0
for p in P:
if p == -1:
ret += 1
U = UnionFind(n)
for i in range(n):
if P[i] != -1:
U.union(P[i] - 1, i)
L = []
for j in range(n):
if P[j] == -1:
L += [U.size[j]]
dp = [0] * (len(L) + 1)
dp[0] = 1
for l in range(1, len(L) + 1):
for m in range(l, 0, -1):
dp[m] += dp[m - 1] * L[l - 1]
if L:
dp[1] = sum(L) - len(L)
cycle_cnt = 0
for i in range(1, len(L) + 1):
cycle_cnt = (cycle_cnt + fac[i - 1] * dp[i] * pow(n - 1, len(L) - i, mod)) % mod
ans = (n - (U.group_num - ret)) * pow(n - 1, ret, mod) % mod
print((ans - cycle_cnt) % mod)
``` | output | 1 | 91,466 | 1 | 182,933 |
Provide a correct Python 3 solution for this coding contest problem.
There are N towns numbered 1, 2, \cdots, N.
Some roads are planned to be built so that each of them connects two distinct towns bidirectionally. Currently, there are no roads connecting towns.
In the planning of construction, each town chooses one town different from itself and requests the following: roads are built so that the chosen town is reachable from itself using one or more roads.
These requests from the towns are represented by an array P_1, P_2, \cdots, P_N. If P_i = -1, it means that Town i has not chosen the request; if 1 \leq P_i \leq N, it means that Town i has chosen Town P_i.
Let K be the number of towns i such that P_i = -1. There are (N-1)^K ways in which the towns can make the requests. For each way to make requests, find the minimum number of roads needed to meet all the requests, and print the sum of those (N-1)^K numbers, modulo (10^9+7).
Constraints
* 2 \leq N \leq 5000
* P_i = -1 or 1 \leq P_i \leq N.
* P_i \neq i
* All values in input are integers.
Input
Input is given from Standard Input in the following format:
N
P_1 P_2 \cdots P_N
Output
For each way to make requests, find the minimum number of roads needed to meet all the requests, and print the sum of those (N-1)^K numbers, modulo (10^9+7).
Examples
Input
4
2 1 -1 3
Output
8
Input
2
2 1
Output
1
Input
10
2 6 9 -1 6 9 -1 -1 -1 -1
Output
527841 | instruction | 0 | 91,467 | 1 | 182,934 |
"Correct Solution:
```
from collections import defaultdict, deque, Counter
from heapq import heappush, heappop, heapify
import math
import bisect
import random
from itertools import permutations, accumulate, combinations, product
import sys
import string
from bisect import bisect_left, bisect_right
from math import factorial, ceil, floor, cos, radians, pi, sin
from operator import mul
from functools import reduce
from operator import mul
from functools import lru_cache
mod = 10 ** 9 + 7
sys.setrecursionlimit(2147483647)
INF = 10 ** 13
def LI(): return list(map(int, sys.stdin.buffer.readline().split()))
def I(): return int(sys.stdin.buffer.readline())
def LS(): return sys.stdin.buffer.readline().rstrip().decode('utf-8').split()
def S(): return sys.stdin.buffer.readline().rstrip().decode('utf-8')
def IR(n): return [I() for i in range(n)]
def LIR(n): return [LI() for i in range(n)]
def SR(n): return [S() for i in range(n)]
def LSR(n): return [LS() for i in range(n)]
def SRL(n): return [list(S()) for i in range(n)]
def MSRL(n): return [[int(j) for j in list(S())] for i in range(n)]
@lru_cache(maxsize=None)
def factorial(n):
if n == 0:
return 1
else:
return (n*factorial(n-1)) % mod
class UnionFind:
def __init__(self, n):
# 負 : 根であることを示す。絶対値はランクを示す
# 非負: 根でないことを示す。値は親を示す
self.table = [-1] * n
self.size = [1] * n
self.group_num = n
def root(self, x):
if self.table[x] < 0:
return x
else:
self.table[x] = self.root(self.table[x])
return self.table[x]
def get_size(self, x):
r = self.root(x)
return self.size[r]
def is_same(self, x, y):
return self.root(x) == self.root(y)
def union(self, x, y):
r1 = self.root(x)
r2 = self.root(y)
if r1 == r2:
return
# ランクの取得
d1 = self.table[r1]
d2 = self.table[r2]
if d1 <= d2:
self.table[r2] = r1
self.size[r1] += self.size[r2]
if d1 == d2:
self.table[r1] -= 1
else:
self.table[r1] = r2
self.size[r2] += self.size[r1]
self.group_num -= 1
n = I()
P = LI()
fac = [1] * (n + 1)
inv = [1] * (n + 1)
for j in range(1, n + 1):
fac[j] = fac[j-1] * j % mod
inv[n] = pow(fac[n], mod-2, mod)
for j in range(n-1, -1, -1):
inv[j] = inv[j+1] * (j+1) % mod
def comb(n, r):
if r > n or n < 0 or r < 0:
return 0
return fac[n] * inv[n - r] * inv[r] % mod
U = UnionFind(n)
for i in range(n):
if P[i] != -1:
U.union(P[i] - 1, i)
k = 0
L = []
for j in range(n):
if P[j] == -1:
L += [U.get_size(j)]
k += 1
dp = [0]*(k+1)
dp[0] = 1
dp_new = dp[:]
for i in range(1, k+1):
for j in range(i):
dp_new[j+1] += dp[j]*L[i-1]
dp = dp_new[:]
if k:
dp[1] = sum(L) - len(L)
cycle_count = 0
for i in range(1, k + 1):
# i個のグループからなるサイクルがひとつできる
buf = dp[i] * factorial(i - 1)
buf %= mod
buf *= pow(n - 1, k - i, mod)
buf %= mod
cycle_count += buf
# すでに固定サイクルがあれば数える
cycle_count += (U.group_num - k) * pow(n - 1, k, mod)
ans = n * pow(n - 1, k, mod)
ans %= mod
ans = ans - cycle_count
ans %= mod
print(ans)
``` | output | 1 | 91,467 | 1 | 182,935 |
Provide a correct Python 3 solution for this coding contest problem.
There are N towns numbered 1, 2, \cdots, N.
Some roads are planned to be built so that each of them connects two distinct towns bidirectionally. Currently, there are no roads connecting towns.
In the planning of construction, each town chooses one town different from itself and requests the following: roads are built so that the chosen town is reachable from itself using one or more roads.
These requests from the towns are represented by an array P_1, P_2, \cdots, P_N. If P_i = -1, it means that Town i has not chosen the request; if 1 \leq P_i \leq N, it means that Town i has chosen Town P_i.
Let K be the number of towns i such that P_i = -1. There are (N-1)^K ways in which the towns can make the requests. For each way to make requests, find the minimum number of roads needed to meet all the requests, and print the sum of those (N-1)^K numbers, modulo (10^9+7).
Constraints
* 2 \leq N \leq 5000
* P_i = -1 or 1 \leq P_i \leq N.
* P_i \neq i
* All values in input are integers.
Input
Input is given from Standard Input in the following format:
N
P_1 P_2 \cdots P_N
Output
For each way to make requests, find the minimum number of roads needed to meet all the requests, and print the sum of those (N-1)^K numbers, modulo (10^9+7).
Examples
Input
4
2 1 -1 3
Output
8
Input
2
2 1
Output
1
Input
10
2 6 9 -1 6 9 -1 -1 -1 -1
Output
527841 | instruction | 0 | 91,468 | 1 | 182,936 |
"Correct Solution:
```
def productall(a):
N = len(a)
if N == 0: return [1]
A = [1] * N + a[:]
P = 10 ** 9 + 7
k = 12
K = k * 8
pa1 = (1 << k * 4 + 16) - ((1 << k * 4 + 16) % P)
pa2 = (1 << k * 2 + 24) - ((1 << k * 2 + 24) % P)
pa3 = (1 << k + 28) - ((1 << k + 28) % P)
def modP(x):
x -= ((x & m1) >> k * 4 + 16) * pa1
x -= ((x & m2) >> k * 2 + 24) * pa2
x -= ((x & m3) >> k + 28) * pa3
return x
c = 3
m1 = int(("1" * (k * 4 - 16) + "0" * (k * 4 + 16)) * c, 2)
m2 = int(("1" * (k * 6 - 24) + "0" * (k * 2 + 24)) * c, 2)
m3 = int(("1" * (k * 7 - 28) + "0" * (k + 28)) * c, 2)
for i in range(1, N)[::-1]:
if i == 1 << i.bit_length() - 1:
c *= 2
m1 = int(("1" * (k * 4 - 16) + "0" * (k * 4 + 16)) * c, 2)
m2 = int(("1" * (k * 6 - 24) + "0" * (k * 2 + 24)) * c, 2)
m3 = int(("1" * (k * 7 - 28) + "0" * (k + 28)) * c, 2)
A[i] = modP(A[2*i] * A[2*i+1])
t = bin(A[1])[2:] + "_"
return [int(t[-(i+1) * K - 1:-i * K - 1], 2) % P for i in range((len(t)+K-2) // K)]
def par(a):
L = []
while P[a] != a:
L.append(a)
a = P[a]
for l in L:
P[l] = a
return a
def unite(a, b):
pa = par(a)
pb = par(b)
if pa == pb: return
if LEN[pa] < LEN[pb]:
a, b, pa, pb = b, a, pb, pa
P[pb] = pa
if LEN[pa] == LEN[pb]: LEN[pa] += 1
CNT[pa] += CNT[pb]
def cnt(a):
return CNT[par(a)]
N = int(input())
P = [i for i in range(N)]
LEN = [1] * N
CNT = [1] * N
FULL = [0] * N
A = [int(a) - 1 for a in input().split()]
for i, a in enumerate(A):
if a < 0: continue
if par(i) != par(a):
unite(i, a)
else:
FULL[i] = 1
for i in range(N):
if FULL[i]:
FULL[par(i)] = 1
X = []
Y = []
for i in range(N):
if par(i) == i:
if FULL[i] == 0:
X.append(CNT[i])
else:
Y.append(CNT[i])
M = len(X)
mod = 10 ** 9 + 7
ans = (sum(X) + sum(Y) - len(Y)) * pow(N - 1, M, mod) % mod
L = productall([(a << 96) + 1 for a in X])
fa = 1
if M: ans = (ans + M * pow(N - 1, M - 1, mod)) % mod
for i, l in enumerate(L):
if i == 0: continue
ans = (ans - l * fa * pow(N - 1, M - i + mod - 1, mod)) % mod
fa = fa * i % mod
print(ans)
``` | output | 1 | 91,468 | 1 | 182,937 |
Provide a correct Python 3 solution for this coding contest problem.
There are N towns numbered 1, 2, \cdots, N.
Some roads are planned to be built so that each of them connects two distinct towns bidirectionally. Currently, there are no roads connecting towns.
In the planning of construction, each town chooses one town different from itself and requests the following: roads are built so that the chosen town is reachable from itself using one or more roads.
These requests from the towns are represented by an array P_1, P_2, \cdots, P_N. If P_i = -1, it means that Town i has not chosen the request; if 1 \leq P_i \leq N, it means that Town i has chosen Town P_i.
Let K be the number of towns i such that P_i = -1. There are (N-1)^K ways in which the towns can make the requests. For each way to make requests, find the minimum number of roads needed to meet all the requests, and print the sum of those (N-1)^K numbers, modulo (10^9+7).
Constraints
* 2 \leq N \leq 5000
* P_i = -1 or 1 \leq P_i \leq N.
* P_i \neq i
* All values in input are integers.
Input
Input is given from Standard Input in the following format:
N
P_1 P_2 \cdots P_N
Output
For each way to make requests, find the minimum number of roads needed to meet all the requests, and print the sum of those (N-1)^K numbers, modulo (10^9+7).
Examples
Input
4
2 1 -1 3
Output
8
Input
2
2 1
Output
1
Input
10
2 6 9 -1 6 9 -1 -1 -1 -1
Output
527841 | instruction | 0 | 91,469 | 1 | 182,938 |
"Correct Solution:
```
import sys
input = lambda : sys.stdin.readline().rstrip()
sys.setrecursionlimit(max(1000, 10**9))
write = lambda x: sys.stdout.write(x+"\n")
class UnionFindTree:
def __init__(self, n):
self.n = n
self.parent = list(range(n))
self.size = [1] * n
def root(self, i):
inter = set()
while self.parent[i]!=i:
inter.add(i)
i = self.parent[i]
r = i
for i in inter:
self.parent[i] = r
return r
def connect(self, i, j):
if i==j:
return
ri = self.root(i)
rj = self.root(j)
if ri==rj:
return
if self.size[ri]<self.size[rj]:
self.parent[ri] = rj
self.size[rj] += self.size[ri]
else:
self.parent[rj] = ri
self.size[ri] += self.size[rj]
n = int(input())
uf = UnionFindTree(n)
ps = list(map(int, input().split()))
k = 0
for i,p in enumerate(ps):
if p<0:
k += 1
continue
uf.connect(i,p-1)
for i in range(n):
uf.root(i)
from collections import Counter, defaultdict
M = 10**9+7
ncount = Counter(uf.parent)
mcount = defaultdict(int)
for i,g in enumerate(uf.parent):
if ps[i]==-1:
mcount[g] += 1
ans = sum(v-1 for v in ncount.values())
ans *= pow(n-1, k, M)
for kk in ncount.keys():
ncount[kk] -= mcount[kk]
for kk,mm in mcount.items():
if mm==0:
continue
nn = ncount[kk]
ans += (n - mm - nn)*pow(n-1, k-1, M)*mm
ans %= M
nums = [nn+mcount[k] for k,nn in ncount.items() if mcount[k]]
l = len(nums)
dp = [[0] * l for _ in range(l)]
# dp[i][j] : i番目まで使うときの周期j+1の個数
if nums:
dp[0][0] = nums[0]
for i in range(1,l):
dp[i][0] = dp[i-1][0] + nums[i]
for i in range(1,l):
for j in range(1,l):
dp[i][j] += dp[i-1][j-1] * nums[i] * j + dp[i-1][j]
dp[i][j] %= M
for j in range(1, l):
ans -= dp[-1][j]*pow(n-1, l-j-1, M)
print(ans%M)
``` | output | 1 | 91,469 | 1 | 182,939 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
There are N towns numbered 1, 2, \cdots, N.
Some roads are planned to be built so that each of them connects two distinct towns bidirectionally. Currently, there are no roads connecting towns.
In the planning of construction, each town chooses one town different from itself and requests the following: roads are built so that the chosen town is reachable from itself using one or more roads.
These requests from the towns are represented by an array P_1, P_2, \cdots, P_N. If P_i = -1, it means that Town i has not chosen the request; if 1 \leq P_i \leq N, it means that Town i has chosen Town P_i.
Let K be the number of towns i such that P_i = -1. There are (N-1)^K ways in which the towns can make the requests. For each way to make requests, find the minimum number of roads needed to meet all the requests, and print the sum of those (N-1)^K numbers, modulo (10^9+7).
Constraints
* 2 \leq N \leq 5000
* P_i = -1 or 1 \leq P_i \leq N.
* P_i \neq i
* All values in input are integers.
Input
Input is given from Standard Input in the following format:
N
P_1 P_2 \cdots P_N
Output
For each way to make requests, find the minimum number of roads needed to meet all the requests, and print the sum of those (N-1)^K numbers, modulo (10^9+7).
Examples
Input
4
2 1 -1 3
Output
8
Input
2
2 1
Output
1
Input
10
2 6 9 -1 6 9 -1 -1 -1 -1
Output
527841
Submitted Solution:
```
def productall(a):
N = len(a)
if N == 0: return [1]
A = [1] * N + a[:]
P = 10 ** 9 + 7
k = 100
K = k * 8
pa1 = (1 << k * 4 + 16) - ((1 << k * 4 + 16) % P)
pa2 = (1 << k * 2 + 24) - ((1 << k * 2 + 24) % P)
pa3 = (1 << k + 28) - ((1 << k + 28) % P)
def modP(x):
x -= ((x & m1) >> k * 4 + 16) * pa1
x -= ((x & m2) >> k * 2 + 24) * pa2
x -= ((x & m3) >> k + 28) * pa3
return x
for i in range(N)[::-1]:
if i == N - 1 or i and 1 << i.bit_length() - 1 == i:
if i == N - 1:
c = 2
else:
c *= 2
m1 = int(("1" * (k * 4 - 16) + "0" * (k * 4 + 16)) * c, 2)
m2 = int(("1" * (k * 6 - 24) + "0" * (k * 2 + 24)) * c, 2)
m3 = int(("1" * (k * 7 - 28) + "0" * (k + 28)) * c, 2)
A[i] = modP(A[2*i] * A[2*i+1])
t = bin(A[1])[2:] + "_"
return [int(t[-(i+1) * K - 1:-i * K - 1], 2) % P for i in range((len(t)+K-2) // K)]
def par(a):
L = []
while P[a] != a:
L.append(a)
a = P[a]
for l in L:
P[l] = a
return a
def unite(a, b):
pa = par(a)
pb = par(b)
if pa == pb: return
if LEN[pa] < LEN[pb]:
a, b, pa, pb = b, a, pb, pa
P[pb] = pa
if LEN[pa] == LEN[pb]: LEN[pa] += 1
CNT[pa] += CNT[pb]
def cnt(a):
return CNT[par(a)]
N = int(input())
P = [i for i in range(N)]
LEN = [1] * N
CNT = [1] * N
FULL = [0] * N
A = [int(a) - 1 for a in input().split()]
for i, a in enumerate(A):
if a < 0: continue
if par(i) != par(a):
unite(i, a)
else:
FULL[i] = 1
for i in range(N):
if FULL[i]:
FULL[par(i)] = 1
X = []
Y = []
for i in range(N):
if par(i) == i:
if FULL[i] == 0:
X.append(CNT[i])
else:
Y.append(CNT[i])
M = len(X)
mod = 10 ** 9 + 7
ans = (sum(X) + sum(Y) - len(Y)) * pow(N - 1, M, mod) % mod
L = productall([(a << 800) + 1 for a in X])
if M:
fa = 1
ans = (ans + M * pow(N - 1, M - 1, mod)) % mod
for i, l in enumerate(L):
if i == 0: continue
ans = (ans - l * fa * pow(N - 1, M - i, mod)) % mod
fa = fa * i % mod
print(ans)
``` | instruction | 0 | 91,470 | 1 | 182,940 |
Yes | output | 1 | 91,470 | 1 | 182,941 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
There are N towns numbered 1, 2, \cdots, N.
Some roads are planned to be built so that each of them connects two distinct towns bidirectionally. Currently, there are no roads connecting towns.
In the planning of construction, each town chooses one town different from itself and requests the following: roads are built so that the chosen town is reachable from itself using one or more roads.
These requests from the towns are represented by an array P_1, P_2, \cdots, P_N. If P_i = -1, it means that Town i has not chosen the request; if 1 \leq P_i \leq N, it means that Town i has chosen Town P_i.
Let K be the number of towns i such that P_i = -1. There are (N-1)^K ways in which the towns can make the requests. For each way to make requests, find the minimum number of roads needed to meet all the requests, and print the sum of those (N-1)^K numbers, modulo (10^9+7).
Constraints
* 2 \leq N \leq 5000
* P_i = -1 or 1 \leq P_i \leq N.
* P_i \neq i
* All values in input are integers.
Input
Input is given from Standard Input in the following format:
N
P_1 P_2 \cdots P_N
Output
For each way to make requests, find the minimum number of roads needed to meet all the requests, and print the sum of those (N-1)^K numbers, modulo (10^9+7).
Examples
Input
4
2 1 -1 3
Output
8
Input
2
2 1
Output
1
Input
10
2 6 9 -1 6 9 -1 -1 -1 -1
Output
527841
Submitted Solution:
```
#!/usr/bin/env python3
import sys
from functools import lru_cache
sys.setrecursionlimit(10**8)
INF = float("inf")
MOD = 1000000007 # type: int
@lru_cache(maxsize=None)
def factorial(n):
if n == 0:
return 1
else:
return (n*factorial(n-1)) % MOD
class UnionFind():
def __init__(self, n):
self.n = n
self.parents = [-1] * n
def find(self, x):
if self.parents[x] < 0:
return x
else:
self.parents[x] = self.find(self.parents[x])
return self.parents[x]
def union(self, x, y):
x = self.find(x)
y = self.find(y)
if x == y:
return
if self.parents[x] > self.parents[y]:
x, y = y, x
self.parents[x] += self.parents[y]
self.parents[y] = x
def size(self, x):
return -self.parents[self.find(x)]
def same(self, x, y):
return self.find(x) == self.find(y)
def members(self, x):
root = self.find(x)
return [i for i in range(self.n) if self.find(i) == root]
def roots(self):
return [i for i, x in enumerate(self.parents) if x < 0]
def group_count(self):
return len(self.roots())
def all_group_members(self):
return {r: self.members(r) for r in self.roots()}
def __str__(self):
return '\n'.join('{}: {}'.format(r, self.members(r)) for r in self.roots())
def main():
N = int(input())
P = list(map(int, input().split()))
# 確定している道でグルーピングする
uf = UnionFind(N)
K = 0
undef = []
for i, p in enumerate(P):
if p != -1:
uf.union(i, p-1)
else:
K += 1
undef.append(i)
groups = {}
mapping = {}
for i, r in enumerate(uf.roots()):
groups[r] = [uf.size(r), True]
mapping[i] = r
for u in undef:
groups[uf.find(u)][1] = False
# 作り直し(むだっぽい)
size_all = []
looped = []
size_undef = []
for k, v in groups.items():
size_all.append(v[0])
looped.append(v[1])
if v[1] == False:
size_undef.append(v[0])
# print(size_all)
# print(looped)
# dp[i, j]: i個の根付き木を見てj個を選んだ時の\sum{\prod_v S_v}
dp = [0]*(K+1)
dp[0] = 1
dp_new = dp[:]
for i in range(1, K+1):
for j in range(i):
dp_new[j+1] += dp[j]*size_undef[i-1]
dp = dp_new[:]
# print("dpしたときのdp", dp)
# ただしj=1個を選んだ時のものは特別にsize[i]-1を考える必要がある
if K >= 1:
tot = 0
for s in size_undef:
tot += s-1
dp[1] = tot
# print("j==1のケースを修正後dp", dp)
cycle_count = 0
for i in range(1, K+1):
# i個のグループからなるサイクルがひとつできる
buf = dp[i]*factorial(i-1)
buf %= MOD
buf *= pow(N-1, K-i, MOD)
buf %= MOD
cycle_count += buf
# print("数え上げ", dp[i], factorial(i-1), pow(N-1, K-i, MOD))
# print(f"cycle_count, {cycle_count}")
# すでに固定サイクルがあれば数える
cycle_count += (len(groups)-K)*pow(N-1, K, MOD)
# \sigma_{つなぎ方} N
ans = N*pow(N-1, K, MOD)
# print("sigma_{つなぎ方} N", ans)
ans %= MOD
ans = ans - cycle_count
ans %= MOD
print(ans)
return
if __name__ == '__main__':
main()
``` | instruction | 0 | 91,471 | 1 | 182,942 |
Yes | output | 1 | 91,471 | 1 | 182,943 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
There are N towns numbered 1, 2, \cdots, N.
Some roads are planned to be built so that each of them connects two distinct towns bidirectionally. Currently, there are no roads connecting towns.
In the planning of construction, each town chooses one town different from itself and requests the following: roads are built so that the chosen town is reachable from itself using one or more roads.
These requests from the towns are represented by an array P_1, P_2, \cdots, P_N. If P_i = -1, it means that Town i has not chosen the request; if 1 \leq P_i \leq N, it means that Town i has chosen Town P_i.
Let K be the number of towns i such that P_i = -1. There are (N-1)^K ways in which the towns can make the requests. For each way to make requests, find the minimum number of roads needed to meet all the requests, and print the sum of those (N-1)^K numbers, modulo (10^9+7).
Constraints
* 2 \leq N \leq 5000
* P_i = -1 or 1 \leq P_i \leq N.
* P_i \neq i
* All values in input are integers.
Input
Input is given from Standard Input in the following format:
N
P_1 P_2 \cdots P_N
Output
For each way to make requests, find the minimum number of roads needed to meet all the requests, and print the sum of those (N-1)^K numbers, modulo (10^9+7).
Examples
Input
4
2 1 -1 3
Output
8
Input
2
2 1
Output
1
Input
10
2 6 9 -1 6 9 -1 -1 -1 -1
Output
527841
Submitted Solution:
```
import sys
INF = 1 << 60
MOD = 10**9 + 7 # 998244353
sys.setrecursionlimit(2147483647)
input = lambda:sys.stdin.readline().rstrip()
class modfact(object):
def __init__(self, n):
fact, invfact = [1] * (n + 1), [1] * (n + 1)
for i in range(1, n + 1): fact[i] = i * fact[i - 1] % MOD
invfact[n] = pow(fact[n], MOD - 2, MOD)
for i in range(n - 1, -1, -1): invfact[i] = invfact[i + 1] * (i + 1) % MOD
self._fact, self._invfact = fact, invfact
def inv(self, n):
return self._fact[n - 1] * self._invfact[n] % MOD
def fact(self, n):
return self._fact[n]
def invfact(self, n):
return self._invfact[n]
def comb(self, n, k):
if k < 0 or n < k: return 0
return self._fact[n] * self._invfact[k] % MOD * self._invfact[n - k] % MOD
def perm(self, n, k):
if k < 0 or n < k: return 0
return self._fact[n] * self._invfact[n - k] % MOD
class UnionFind(object):
def __init__(self, n, recursion = False):
self._par = list(range(n))
self._size = [1] * n
self._recursion = recursion
def root(self, k):
if self._recursion:
if k == self._par[k]:
return k
self._par[k] = self.root(self._par[k])
return self._par[k]
else:
root = k
while root != self._par[root]: root = self._par[root]
while k != root: k, self._par[k] = self._par[k], root
return root
def unite(self, i, j):
i, j = self.root(i), self.root(j)
if i == j: return False
if self._size[i] < self._size[j]: i, j = j, i
self._par[j] = i
self._size[i] += self._size[j]
return True
def is_connected(self, i, j):
return self.root(i) == self.root(j)
def size(self, k):
return self._size[self.root(k)]
def resolve():
n = int(input())
P = [a - 1 if a != -1 else -1 for a in map(int, input().split())]
k = P.count(-1)
E = [[] for _ in range(n)]
for u, v in enumerate(P):
if v != -1:
E[u].append(v)
E[v].append(u)
# divide E into connected component
color = [-1] * n
cnt = 0
def dfs(v):
if color[v] != -1:
return False
color[v] = cnt
stack = [v]
while stack:
v = stack.pop()
for nv in E[v]:
if color[nv] == -1:
color[nv] = cnt
stack.append(nv)
return True
for v in range(n):
cnt += dfs(v)
# detect loops for each color with union find
has_loop = [False] * cnt
uf = UnionFind(n)
for v in range(n):
nv = P[v]
if nv == -1:
continue
if not uf.unite(v, nv):
has_loop[color[v]] = True
S = []
for root in set(uf.root(v) for v in range(n)):
if not has_loop[color[root]]:
S.append(uf.size(root))
ans = pow(n - 1, k, MOD) * (n - sum(has_loop))
l = len(S)
dp = [0] * (l + 1)
dp[0] = 1
for s in S:
ndp = dp[:]
for i in range(1, l + 1):
ndp[i] += s * dp[i - 1]
ndp[i] %= MOD
dp = ndp
# i >= 2
mf = modfact(5001)
for i in range(1, l + 1):
if i == 1:
ans -= sum(s - 1 for s in S) % MOD * pow(n - 1, k - 1, MOD)
else:
ans -= dp[i] * mf.fact(i - 1) % MOD * pow(n - 1, k - i, MOD)
ans %= MOD
print(ans)
resolve()
``` | instruction | 0 | 91,472 | 1 | 182,944 |
Yes | output | 1 | 91,472 | 1 | 182,945 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
There are N towns numbered 1, 2, \cdots, N.
Some roads are planned to be built so that each of them connects two distinct towns bidirectionally. Currently, there are no roads connecting towns.
In the planning of construction, each town chooses one town different from itself and requests the following: roads are built so that the chosen town is reachable from itself using one or more roads.
These requests from the towns are represented by an array P_1, P_2, \cdots, P_N. If P_i = -1, it means that Town i has not chosen the request; if 1 \leq P_i \leq N, it means that Town i has chosen Town P_i.
Let K be the number of towns i such that P_i = -1. There are (N-1)^K ways in which the towns can make the requests. For each way to make requests, find the minimum number of roads needed to meet all the requests, and print the sum of those (N-1)^K numbers, modulo (10^9+7).
Constraints
* 2 \leq N \leq 5000
* P_i = -1 or 1 \leq P_i \leq N.
* P_i \neq i
* All values in input are integers.
Input
Input is given from Standard Input in the following format:
N
P_1 P_2 \cdots P_N
Output
For each way to make requests, find the minimum number of roads needed to meet all the requests, and print the sum of those (N-1)^K numbers, modulo (10^9+7).
Examples
Input
4
2 1 -1 3
Output
8
Input
2
2 1
Output
1
Input
10
2 6 9 -1 6 9 -1 -1 -1 -1
Output
527841
Submitted Solution:
```
#!/usr/bin/env python3
import sys
sys.setrecursionlimit(10**8)
INF = float("inf")
MOD = 1000000007 # type: int
class UnionFind():
def __init__(self, n):
self.n = n
self.parents = [-1] * n
def find(self, x):
if self.parents[x] < 0:
return x
else:
self.parents[x] = self.find(self.parents[x])
return self.parents[x]
def union(self, x, y):
x = self.find(x)
y = self.find(y)
if x == y:
return
if self.parents[x] > self.parents[y]:
x, y = y, x
self.parents[x] += self.parents[y]
self.parents[y] = x
def size(self, x):
return -self.parents[self.find(x)]
def same(self, x, y):
return self.find(x) == self.find(y)
def members(self, x):
root = self.find(x)
return [i for i in range(self.n) if self.find(i) == root]
def roots(self):
return [i for i, x in enumerate(self.parents) if x < 0]
def group_count(self):
return len(self.roots())
def all_group_members(self):
return {r: self.members(r) for r in self.roots()}
def __str__(self):
return '\n'.join('{}: {}'.format(r, self.members(r)) for r in self.roots())
def main():
N = int(input())
P = list(map(int, input().split()))
# 確定している道でグルーピングする
uf = UnionFind(N)
K = 0
undef = [] # 要請未完ノードは記録
for i, p in enumerate(P):
if p != -1:
uf.union(i, p-1)
else:
K += 1
undef.append(i)
# 階乗の事前計算
factorial = [1]*K
for i in range(K-1):
factorial[i+1] = ((i+1)*factorial[i]) % MOD
# 要請が未完のノードが属するグループサイズをメモ
size_undef = []
for u in undef:
size_undef.append(uf.size(u))
# dp[i, j]: i個の根付き木を見てj個を選んだ時の\sum{\prod_v S_v}
# 「メモリ削減したdpとN^2確保するDP、どっちが早いんやろなあ」
dp = [0]*(K+1)
dp[0] = 1
dp_new = dp[:]
for i in range(1, K+1):
for j in range(i):
dp_new[j+1] += dp[j]*size_undef[i-1]
dp = dp_new[:]
# ただしj=1個を選んだ時のものは特別にsize[i]-1を考える必要がある
if K >= 1:
tot = 0
for s in size_undef:
tot += s-1
dp[1] = tot
# cycleをカウントする
cycle_count = 0
for i in range(1, K+1):
# i個のグループからなるサイクルがひとつできる
buf = dp[i]*factorial[i-1]
buf %= MOD
buf *= pow(N-1, K-i, MOD)
buf %= MOD
cycle_count += buf
# すでに固定サイクルがあれば数える
cycle_count += (uf.group_count()-K)*pow(N-1, K, MOD)
# 求めます
ans = N*pow(N-1, K, MOD) - cycle_count
ans %= MOD
print(ans)
return
if __name__ == '__main__':
main()
``` | instruction | 0 | 91,473 | 1 | 182,946 |
Yes | output | 1 | 91,473 | 1 | 182,947 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
There are N towns numbered 1, 2, \cdots, N.
Some roads are planned to be built so that each of them connects two distinct towns bidirectionally. Currently, there are no roads connecting towns.
In the planning of construction, each town chooses one town different from itself and requests the following: roads are built so that the chosen town is reachable from itself using one or more roads.
These requests from the towns are represented by an array P_1, P_2, \cdots, P_N. If P_i = -1, it means that Town i has not chosen the request; if 1 \leq P_i \leq N, it means that Town i has chosen Town P_i.
Let K be the number of towns i such that P_i = -1. There are (N-1)^K ways in which the towns can make the requests. For each way to make requests, find the minimum number of roads needed to meet all the requests, and print the sum of those (N-1)^K numbers, modulo (10^9+7).
Constraints
* 2 \leq N \leq 5000
* P_i = -1 or 1 \leq P_i \leq N.
* P_i \neq i
* All values in input are integers.
Input
Input is given from Standard Input in the following format:
N
P_1 P_2 \cdots P_N
Output
For each way to make requests, find the minimum number of roads needed to meet all the requests, and print the sum of those (N-1)^K numbers, modulo (10^9+7).
Examples
Input
4
2 1 -1 3
Output
8
Input
2
2 1
Output
1
Input
10
2 6 9 -1 6 9 -1 -1 -1 -1
Output
527841
Submitted Solution:
```
N = input(int())
A = list(map(int, input().split()))
count = 0
B3 = 0
for i in A:
count += i + 1
print(count)
``` | instruction | 0 | 91,474 | 1 | 182,948 |
No | output | 1 | 91,474 | 1 | 182,949 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
There are N towns numbered 1, 2, \cdots, N.
Some roads are planned to be built so that each of them connects two distinct towns bidirectionally. Currently, there are no roads connecting towns.
In the planning of construction, each town chooses one town different from itself and requests the following: roads are built so that the chosen town is reachable from itself using one or more roads.
These requests from the towns are represented by an array P_1, P_2, \cdots, P_N. If P_i = -1, it means that Town i has not chosen the request; if 1 \leq P_i \leq N, it means that Town i has chosen Town P_i.
Let K be the number of towns i such that P_i = -1. There are (N-1)^K ways in which the towns can make the requests. For each way to make requests, find the minimum number of roads needed to meet all the requests, and print the sum of those (N-1)^K numbers, modulo (10^9+7).
Constraints
* 2 \leq N \leq 5000
* P_i = -1 or 1 \leq P_i \leq N.
* P_i \neq i
* All values in input are integers.
Input
Input is given from Standard Input in the following format:
N
P_1 P_2 \cdots P_N
Output
For each way to make requests, find the minimum number of roads needed to meet all the requests, and print the sum of those (N-1)^K numbers, modulo (10^9+7).
Examples
Input
4
2 1 -1 3
Output
8
Input
2
2 1
Output
1
Input
10
2 6 9 -1 6 9 -1 -1 -1 -1
Output
527841
Submitted Solution:
```
MOD = 10 ** 9 + 7
N = int(input())
d = dict()
P = tuple(map(int, input().split()))
for i, p in enumerate(P, 1):
if p == -1:
d[i] = 0
target = [0] * (N + 1)
roads = 0
for i, p in enumerate(P, 1):
if p != -1 and target[p] != i:
if p in d.keys():
d[p] += 1
target[i] = p
roads += 1
d2 = dict()
for i, (k, v) in enumerate(d.items()):
d2[k] = N - 1 - v - i
if not d2:
print(1)
quit()
K = i + 1
table = [[0] * (K + 1) for _ in range(K + 1)]
table[0][0] = 1
for k in range(K):
for i, p in enumerate(d2.values()):
table[i + 1][k] = (table[i + 1][k] + table[i][k] * (N - 1 - p)) % MOD
table[i + 1][k + 1] += table[i][k] * p
table[i + 1][k + 1] %= MOD
total = 0
for i in range(K + 1):
total = (total + (roads + i) * table[K][i]) % MOD
print(total)
``` | instruction | 0 | 91,475 | 1 | 182,950 |
No | output | 1 | 91,475 | 1 | 182,951 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
There are N towns numbered 1, 2, \cdots, N.
Some roads are planned to be built so that each of them connects two distinct towns bidirectionally. Currently, there are no roads connecting towns.
In the planning of construction, each town chooses one town different from itself and requests the following: roads are built so that the chosen town is reachable from itself using one or more roads.
These requests from the towns are represented by an array P_1, P_2, \cdots, P_N. If P_i = -1, it means that Town i has not chosen the request; if 1 \leq P_i \leq N, it means that Town i has chosen Town P_i.
Let K be the number of towns i such that P_i = -1. There are (N-1)^K ways in which the towns can make the requests. For each way to make requests, find the minimum number of roads needed to meet all the requests, and print the sum of those (N-1)^K numbers, modulo (10^9+7).
Constraints
* 2 \leq N \leq 5000
* P_i = -1 or 1 \leq P_i \leq N.
* P_i \neq i
* All values in input are integers.
Input
Input is given from Standard Input in the following format:
N
P_1 P_2 \cdots P_N
Output
For each way to make requests, find the minimum number of roads needed to meet all the requests, and print the sum of those (N-1)^K numbers, modulo (10^9+7).
Examples
Input
4
2 1 -1 3
Output
8
Input
2
2 1
Output
1
Input
10
2 6 9 -1 6 9 -1 -1 -1 -1
Output
527841
Submitted Solution:
```
from collections import defaultdict, deque, Counter
from heapq import heappush, heappop, heapify
import math
import bisect
import random
from itertools import permutations, accumulate, combinations, product
import sys
import string
from bisect import bisect_left, bisect_right
from math import factorial, ceil, floor, cos, radians, pi, sin
from operator import mul
from functools import reduce
from operator import mul
mod = 10 ** 9 + 7
sys.setrecursionlimit(2147483647)
INF = 10 ** 13
def LI(): return list(map(int, sys.stdin.buffer.readline().split()))
def I(): return int(sys.stdin.buffer.readline())
def LS(): return sys.stdin.buffer.readline().rstrip().decode('utf-8').split()
def S(): return sys.stdin.buffer.readline().rstrip().decode('utf-8')
def IR(n): return [I() for i in range(n)]
def LIR(n): return [LI() for i in range(n)]
def SR(n): return [S() for i in range(n)]
def LSR(n): return [LS() for i in range(n)]
def SRL(n): return [list(S()) for i in range(n)]
def MSRL(n): return [[int(j) for j in list(S())] for i in range(n)]
class UnionFind:
def __init__(self, n):
self.par = [i for i in range(n)]
self.rank = [0] * (n)
self.size = [1] * n
self.group_num = n
# 検索
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 = self.find(x)
y = self.find(y)
if self.rank[x] < self.rank[y]:
self.par[x] = y
self.size[y] += self.size[x]
else:
self.par[y] = x
self.size[x] += self.size[y]
if self.rank[x] == self.rank[y]:
self.rank[x] += 1
self.group_num -= 1
n = I()
P = LI()
fac = [1] * (n + 1)
inv = [1] * (n + 1)
for j in range(1, n + 1):
fac[j] = fac[j-1] * j % mod
inv[n] = pow(fac[n], mod-2, mod)
for j in range(n-1, -1, -1):
inv[j] = inv[j+1] * (j+1) % mod
def comb(n, r):
if r > n or n < 0 or r < 0:
return 0
return fac[n] * inv[n - r] * inv[r] % mod
ret = 0
for p in P:
if p == -1:
ret += 1
U = UnionFind(n)
for i in range(n):
if P[i] != -1:
U.union(P[i] - 1, i)
L = []
for j in range(n):
if P[j] == -1:
L += [U.size[j]]
dp = [0] * (len(L) + 1)
dp[0] = 1
for l in range(1, len(L) + 1):
for m in range(l, 0, -1):
dp[m] += dp[m - 1] * L[l - 1]
if L:
dp[1] = sum(L) - len(L)
cycle_cnt = 0
for i in range(1, len(L) + 1):
cycle_cnt = (cycle_cnt + fac[i - 1] * dp[i] * pow(n - 1, len(L) - i, mod)) % mod
ans = (n - (U.group_num - ret)) * pow(n - 1, ret, mod) % mod
print((ans - cycle_cnt) % mod)
``` | instruction | 0 | 91,476 | 1 | 182,952 |
No | output | 1 | 91,476 | 1 | 182,953 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.