Problem:


Score : 600 points

Problem Statement

We have a tree with N vertices. The i-th edge connects Vertex A_i and B_i bidirectionally.

Takahashi is standing at Vertex u, and Aoki is standing at Vertex v.

Now, they will play a game of tag as follows:

1. If Takahashi and Aoki are standing at the same vertex, the game ends. Otherwise, Takahashi moves to a vertex of his choice that is adjacent to his current vertex.

2. If Takahashi and Aoki are standing at the same vertex, the game ends. Otherwise, Aoki moves to a vertex of his choice that is adjacent to his current vertex.

3. Go back to step 1.

Takahashi performs his moves so that the game ends as late as possible, while Aoki performs his moves so that the game ends as early as possible.

Find the number of moves Aoki will perform before the end of the game if both Takahashi and Aoki know each other's position and strategy.

It can be proved that the game is bound to end.

Constraints

2 \leq N \leq 10^5

1 \leq u,v \leq N

u \neq v

1 \leq A_i,B_i \leq N

The given graph is a tree.

Input

Input is given from Standard Input in the following format:

N u v
A_1 B_1
:
A_{N-1} B_{N-1}

Output

Print the number of moves Aoki will perform before the end of the game.

Sample Input 1

5 4 1
1 2
2 3
3 4
3 5

Sample Output 1

2

If both players play optimally, the game will progress as follows:

Takahashi moves to Vertex 3.

Aoki moves to Vertex 2.

Takahashi moves to Vertex 5.

Aoki moves to Vertex 3.

Takahashi moves to Vertex 3.

Here, Aoki performs two moves.

Note that, in each move, it is prohibited to stay at the current vertex.

Sample Input 2

5 4 5
1 2
1 3
1 4
1 5

Sample Output 2

1

Sample Input 3

2 1 2
1 2

Sample Output 3

0

Sample Input 4

9 6 1
1 2
2 3
3 4
4 5
5 6
4 7
7 8
8 9

Sample Output 4

5



Sample input:
5 4 1
1 2
2 3
3 4
3 5


Sample output:
2

Submission status: Runtime Error

Solution code:
import sys
input = sys.stdin.readline

n,u,v = ( int(x) for x in input().split() )

u,v = u-1,v-1

# -1なら行先なし
a = [[] for i in range(n)]
b = [[] for i in range(n)]

for i in range(n-1):
	# 配列indexは0開始だからinputは-1
	l,m = ( int(x)-1 for x in input().split() )
	a[l].append(m)
	a[m].append(l)

# G:graph, cr:current node, seen:pathed or not, dist:out;each distance
def distance(G,cr,seen,dist):
	seen[cr] = 1
	for i in G[cr]: #G[cr]から行ける各頂点へ
		if seen[i] == 0:# or dist[i] > dist[cr]+1: #まだ通っていなかったら
			dist[i] = dist[cr]+1
			distance(G,i,seen,dist)

# 欲しいのはdist of u-v, back way of u
# u視点のdistを調べる
dist_v = [0]*(n)
distance(a,v,[0]*(n),dist_v)
# v視点のdistを調べる
dist_u = [0]*(n)
distance(a,u,[0]*(n),dist_u)

for i in range(n):
	if dist_u[i] >= dist_v[i]:
		dist_u[i] = -1

tmp = max(dist_u)
max_idx = dist_u.index(tmp)

print(dist_v[max_idx] - 1)

Submission status: Runtime Error

Solution code:
import sys
input = sys.stdin.readline

n,u,v = ( int(x) for x in input().split() )

u,v = u-1,v-1

# -1なら行先なし
a = [[] for i in range(n)]
b = [[] for i in range(n)]

for i in range(n-1):
	# 配列indexは0開始だからinputは-1
	l,m = ( int(x)-1 for x in input().split() )
	a[l].append(m)
	a[m].append(l)

def distance(cr,p,dist): # cr:current node, p:pathed or not, dist:out;each distance
	for i in a[cr]: #a[cr]から行ける各頂点へ
		p[cr] = 1
		if p[i] == 0 or dist[i] > dist[cr]+1: #まだ通っていなかったら
			p[i] = 1
			dist[i] = dist[cr]+1
			distance(i,p,dist)

# 欲しいのはdist of u-v, back way of u
# u視点のdistを調べる
p = [0]*(n)
dist_v = [0]*(n)
distance(v,p,dist_v)
# v視点のdistを調べる
p = [0]*(n)
dist_u = [0]*(n)
distance(u,p,dist_u)

for i in range(n):
	if dist_u[i] >= dist_v[i]:
		dist_u[i] = -1

tmp = max(dist_u)
max_idx = dist_u.index(tmp)

print(dist_v[max_idx] - 1)

Submission status: Runtime Error

Solution code:
from collections import deque

n,u,v = map(int,input().split())
edge = [[] for _ in range(n+1)]
for i in range(n-1):
    a,b = map(int,input().split())
    edge[a].append(b)
    edge[b].append(a)
q = deque()
step = [0 for _ in range(n+1)]
q.appendleft([v,0])
visied = set()
visied.add(v)
while len(q)>0:
    a,v = q.pop()
    for node in edge[a]:
        if node not in visied:
            step[node] = v+1
            q.appendleft([node,v+1])
            visied.add(node)           
q =[]
q.appendleft((u,0))
mx= 0
queue = set()
queue.add((u,0))
while len(q)>0:
    a, v = q.pop()
    p=0
    value =0
    for node in edge[a]:
        cur = v+1
        if cur<step[node]:
            add = (node,cur)
            if add not in queue:
                q.appendleft(add)
                queue.add(add)
                p=1
        else:
            value = max(value,step[node])
    if p ==0:
        mx = max(mx,value)
# print(step)
print(mx)

Submission status: Runtime Error

Solution code:
from collections import deque

n,u,v = map(int,input().split())
edge = [[] for _ in range(n+1)]
for i in range(n-1):
    a,b = map(int,input().split())
    edge[a].append(b)
    edge[b].append(a)
q = deque()
step = [0 for _ in range(n+1)]
q.appendLeft([v,0])
visied = set()
visied.add(v)
while len(q)>0:
    a,v = q.pop()
    for node in edge[a]:
        if node not in visied:
            step[node] = v+1
            q.appendLeft([node,v+1])
            visied.add(node)           
q =[]
q.appendLeft((u,0))
mx= 0
queue = set()
queue.add((u,0))
while len(q)>0:
    a, v = q.pop()
    p=0
    value =0
    for node in edge[a]:
        cur = v+1
        if cur<step[node]:
            add = (node,cur)
            if add not in queue:
                q.appendLeft(add)
                queue.add(add)
                p=1
        else:
            value = max(value,step[node])
    if p ==0:
        mx = max(mx,value)
# print(step)
print(mx)

Submission status: Runtime Error

Solution code:
import sys
input = sys.stdin.readline

n,u,v = ( int(x) for x in input().split() )

u,v = u-1,v-1

# -1なら行先なし
a = [[] for i in range(n)]
b = [[] for i in range(n)]

for i in range(n-1):
	# 配列indexは0開始だからinputは-1
	l,m = ( int(x)-1 for x in input().split() )
	a[l].append(m)
	a[m].append(l)


def distance(cr,p,dist): # cr:current node, p:pathed or not, dist:out;each distance
	for i in a[cr]: #a[cr]から行ける各頂点へ
		p[cr] = 1
		if p[i] == 0: #まだ通っていなかったら
			p[i] = 1
			dist[i] = dist[cr]+1
			distance(i,p,dist)

# 欲しいのはdist of u-v, back way of u
# u視点のdistを調べる
p = [0]*(n)
dist_v = [0]*(n)
distance(v,p,dist_v)
# v視点のdistを調べる
p = [0]*(n)
dist_u = [0]*(n)
distance(u,p,dist_u)

for i in range(n):
	if dist_u[i] >= dist_v[i]:
		dist_u[i] = -1

tmp = max(dist_u)
max_idx = dist_u.index(tmp)

print(dist_v[max_idx] - 1)

Submission status: Runtime Error

Solution code:
import sys
input = sys.stdin.readline
import numpy as np

n,u,v = ( int(x) for x in input().split() )

u,v = u-1,v-1

a = [[] for i in range(n)]
b = [[] for i in range(n)]

for i in range(n-1):
	# 配列indexは0開始だからinputは-1
	l,m = ( int(x)-1 for x in input().split() )
	a[l].append(m)
	a[m].append(l)

def distance(cr,p,dist): # cr:current node, p:pathed or not, dist:out;each distance
	for i in a[cr]: #a[cr]から行ける各頂点へ
		p[cr] = 1
		if p[i] == 0: #まだ通っていなかったら
			p[i] = 1
			dist[i] = dist[cr]+1
			distance(i,p,dist)

p = [0]*(n)
dist_v = [0]*(n)
distance(v,p,dist_v)
p = [0]*(n)
dist_u = [0]*(n)
distance(u,p,dist_u)

for i in range(n):
	if dist_u[i] >= dist_v[i]:
		dist_u[i] = -1

tmp = max(dist_u)
max_idx = dist_u.index(tmp)

print(dist_v[max_idx] - 1)

Submission status: Runtime Error

Solution code:
def dps(no, fno, d, hen, D, MD, P):
    D[no] = d
    P[no] = fno
    maxd = d
    for h in hen[no]:
        if h == fno:
            continue
        maxd = max(maxd, dps(h, no, d + 1, hen, D, MD, P))
    MD[no] = maxd
    return maxd


def main():
    N, u, v = map(int, input().split())
    hen = {}
    for i in range(N - 1):
        A, B = map(int, input().split())
        if A in hen.keys():
            hen[A].append(B)
        else:
            hen[A] = [B]
        if B in hen.keys():
            hen[B].append(A)
        else:
            hen[B] = [A]
    DEPTH = [-1 for i in range(N + 1)]
    MAX_DEPTH = [-1 for i in range(N + 1)]
    Parent = [-1 for i in range(N + 1)]
    dps(v, -1, 0, hen, DEPTH, MAX_DEPTH, Parent)
    ans = DEPTH[u]
    p = u
    for i in range((DEPTH[u] + 1) // 2 - 1):
        p = Parent[p]
        ans = max(ans, MAX_DEPTH[p])
    print(ans - 1)

if __name__ == '__main__':
    main()

Submission status: Runtime Error

Solution code:
def dps(no, fno, d, hen, D, MD, P):
    D[no] = d
    P[no] = fno
    maxd = d
    for h in hen[no]:
        if h == fno:
            continue
        maxd = max(maxd, dps(h, no, d + 1, hen, D, MD, P))
    MD[no] = maxd
    return maxd


def main():
    import my_method
    N, u, v = map(int, my_method.input().split())
    hen = {}
    for i in range(N - 1):
        A, B = map(int, my_method.input().split())
        if A in hen.keys():
            hen[A].append(B)
        else:
            hen[A] = [B]
        if B in hen.keys():
            hen[B].append(A)
        else:
            hen[B] = [A]
    DEPTH = [-1 for i in range(N + 1)]
    MAX_DEPTH = [-1 for i in range(N + 1)]
    Parent = [-1 for i in range(N + 1)]
    dps(v, -1, 0, hen, DEPTH, MAX_DEPTH, Parent)
    ans = DEPTH[u]
    p = u
    for i in range((DEPTH[u] + 1) // 2 - 1):
        p = Parent[p]
        ans = max(ans, MAX_DEPTH[p])
    print(ans - 1)

if __name__ == '__main__':
    main()

Submission status: Runtime Error

Solution code:
def dfs(v, d=0, p=-1):
    global dist
    dist[v] = d
    for u in to[v]:
        if u == p:
            continue
        dfs(u, d+1, v)


def calcDist(s):
    global dist
    dist = [0 for _ in range(N)]
    dfs(s)
    return dist


N, s, t = map(int, input().split())
s -= 1
t -= 1
to = [[] for _ in range(N)]
dist = [0 for _ in range(N)]


for i in range(N-1):
    a, b = map(int, input().split())
    a -= 1
    b -= 1
    to[a].append(b)
    to[b].append(a)

distS = calcDist(s)
distT = calcDist(t)

mx = 0
for i in range(N):
    if distS[i] < distT[i]:
        mx = max(mx, distT[i])

ans = mx - 1
print(ans)

Submission status: Runtime Error

Solution code:
n,u,v = map(int,input().split())
u-=1
v-=1
ki = [[]for i in range(n)]
distt = [0]*n
dista = [0]*n
for i in range(n-1):
    a,b = map(int,input().split())
    a -= 1
    b -= 1
    ki[a].append(b)
    ki[b].append(a)
def dfst(now,last = -1):
    for next in ki[now]:
        if next == last:continue
        distt[next] = distt[now]+1
        dfst(next,now)
def dfsa(now,last = -1):
    for next in ki[now]:
        if next == last:continue
        dista[next] = dista[now]+1
        dfsa(next,now)
    
dfst(u)
dfsa(v)
ans = 0
for i in range(n):
    if dista[i]<=distt[i]:continue
    ans = max(ans,dista[i]-1)
print(ans)

Submission status: Runtime Error

Solution code:
import sys
sys.setrecursionlimit(10**7)
n,u,v = map(int,input().split())
ki = [[]for i in range(n)]
distt = [0]*n
dista = [0]*n
for i in range(n-1):
    a,b = map(int,input().split())
    a -= 1
    b -= 1
    ki[a].append(b)
    ki[b].append(a)
def dfst(now,last = -1):
    for next in ki[now]:
        if next == last:continue
        distt[next] = distt[now]+1
        dfst(next,now)
def dfsa(now,last = -1):
    for next in ki[now]:
        if next == last:continue
        dista[next] = dista[now]+1
        dfsa(next,now)
    
dfst(u)
dfsa(v)
ans = 0
for i in range(n):
    if dista[i]<=distt[i]:continue
    ans = max(ans,dista[i]-1)
print(ans)

Submission status: Runtime Error

Solution code:
#!/usr/bin/env python
# coding: utf-8

# In[1]:
import sys
sys.setrecursionlimit(10000)


N, u, v = map(int, input().split())
u = u - 1
v = v - 1


# In[2]:


eda = [[] for _ in range(N)]
for _ in range(N-1):
    A, B = map(int, input().split())
    eda[A-1].append(B-1)
    eda[B-1].append(A-1)


# In[3]:


eda


# In[ ]:





# In[4]:


def dfs(n1, n0):
    houmon[n1] = True
    par[n1] = n0
    for n2 in eda[n1]:
        if not houmon[n2]:
            dfs(n2, n1)
    


# In[5]:


houmon = [False] * N
par = [0] * N
dfs(v, v)


# In[6]:


par


# In[7]:


dis = 0
n = u
while n != v:
    n = par[n]
    dis += 1


# In[8]:


dis


# In[9]:


n = u
for _ in range((dis - 1) // 2):
    n = par[n]


# In[10]:


n


# In[11]:


def dfs2(n1):
    ret = 0
    for n2 in eda[n1]:
        if n2 == par[n1]:
            continue
        ret = max(ret, dfs2(n2) + 1)
    return ret


# In[12]:


y = (dis - 1) // 2
x = dis - y
z = dfs2(n)


# In[13]:


print(y + z + 1 if dis % 2 == 0 else y + z)

Submission status: Runtime Error

Solution code:
#!/usr/bin/env python
# coding: utf-8

# In[1]:


N, u, v = map(int, input().split())
u = u - 1
v = v - 1


# In[2]:


eda = [[] for _ in range(N)]
for _ in range(N-1):
    A, B = map(int, input().split())
    eda[A-1].append(B-1)
    eda[B-1].append(A-1)


# In[3]:


eda


# In[ ]:





# In[4]:


def dfs(n1, n0):
    houmon[n1] = True
    par[n1] = n0
    for n2 in eda[n1]:
        if not houmon[n2]:
            dfs(n2, n1)
    


# In[5]:


houmon = [False] * N
par = [0] * N
dfs(v, v)


# In[6]:


par


# In[7]:


dis = 0
n = u
while n != v:
    n = par[n]
    dis += 1


# In[8]:


dis


# In[9]:


n = u
for _ in range((dis - 1) // 2):
    n = par[n]


# In[10]:


n


# In[11]:


def dfs2(n1):
    ret = 0
    for n2 in eda[n1]:
        if n2 == par[n1]:
            continue
        ret = max(ret, dfs2(n2) + 1)
    return ret


# In[12]:


y = (dis - 1) // 2
x = dis - y
z = dfs2(n)


# In[13]:


print(y + z + 1 if dis % 2 == 0 else y + z)

Submission status: Runtime Error

Solution code:
import sys

sys.setrecursionlimit(10**10)

n, u, v = map(int, input().split())

# nodeの値を-1しておく
u = u-1
v = v-1

# Making Adjacency list
Adj_dict = {}
for i in range(n):
    new = {i: []}
    Adj_dict.update(new)

for _ in range(n-1):
    a, b = map(int, input().split())
    Adj_dict[a-1].append(b-1)
    Adj_dict[b-1].append(a-1)


def tree_distance(Adj_dict, start, Visited, distance, Dist_list):
    
    # 現在いる位置を Visited = True に変更する
    Visited[start] = True

    # 該当するnodeの距離を記録して、distanceを1加算する
    Dist_list[start] = distance
    distance += 1

    # 訪れていないnodeに対して、dfs
    for node in Adj_dict[start]:
        if Visited[node] == False:
            tree_distance(Adj_dict, node, Visited, distance, Dist_list)
    
    return


Dist_list = [0 for _ in range(n)]
Visited = [False for _ in range(n)]
distance = 0
tree_distance(Adj_dict, u, Visited, distance, Dist_list)
Taka = Dist_list

Dist_list = [0 for _ in range(n)]
Visited = [False for _ in range(n)]
distance = 0
tree_distance(Adj_dict, v, Visited, distance, Dist_list)
Aoki = Dist_list

Taka_num = 0
node = 0
for i in range(n):
    if Aoki[i] >= Taka[i]:
        if Taka[i] >= Taka_num:
            Taka_num = Taka[i]
            node = i

# TakahashiはTaka_numのnodeへ逃げる
ans = Aoki[node] -1

print(ans)

Submission status: Runtime Error

Solution code:
n, u, v = map(int, input().split())

# nodeの値を-1しておく
u = u-1
v = v-1

# Making Adjacency list
Adj_dict = {}
for i in range(n):
    new = {i: []}
    Adj_dict.update(new)

for _ in range(n-1):
    a, b = map(int, input().split())
    Adj_dict[a-1].append(b-1)
    Adj_dict[b-1].append(a-1)

def tree_distance(Adj_dict, start, Visited, distance, Dist_list):
    
    if Visited[start] == True:
        return
    
    # 現在いる位置を Visited = True に変更する
    Visited[start] = True

    # 該当するnodeの距離を記録して、distanceを1加算する
    Dist_list[start] = distance
    distance += 1

    # 訪れていないnodeに対して、dfs
    for node in Adj_dict[start]:
        if Visited[node] == False:
            tree_distance(Adj_dict, node, Visited, distance, Dist_list)
    
    return


Dist_list = [0 for _ in range(n)]
Visited = [False for _ in range(n)]
distance = 0
tree_distance(Adj_dict, u, Visited, distance, Dist_list)
Taka = Dist_list

Dist_list = [0 for _ in range(n)]
Visited = [False for _ in range(n)]
distance = 0
tree_distance(Adj_dict, v, Visited, distance, Dist_list)
Aoki = Dist_list

Taka_num = 0
node = 0
for i in range(n):
    if Aoki[i] >= Taka[i]:
        if Taka[i] >= Taka_num:
            Taka_num = Taka[i]
            node = i

# TakahashiはTaka_numのnodeへ逃げる
ans = Aoki[node] -1

print(ans)

Submission status: Runtime Error

Solution code:
n, u, v = map(int, input().split())

# nodeの値を-1しておく
u = u-1
v = v-1

# Making Adjacency list
Adj_dict = {}
for i in range(n):
    new = {i: []}
    Adj_dict.update(new)

for _ in range(n-1):
    a, b = map(int, input().split())
    Adj_dict[a-1].append(b-1)
    Adj_dict[b-1].append(a-1)

def tree_distance(Adj_dict, start, Visited, distance, Dist_list):
    
    # 現在いる位置を Visited = True に変更する
    Visited[start] = True

    # 該当するnodeの距離を記録して、distanceを1加算する
    Dist_list[start] = distance
    distance += 1

    # 訪れていないnodeに対して、dfs
    for node in Adj_dict[start]:
        if Visited[node] == False:
            tree_distance(Adj_dict, node, Visited, distance, Dist_list)
    
    return


Dist_list = [0 for _ in range(n)]
Visited = [False for _ in range(n)]
distance = 0
tree_distance(Adj_dict, u, Visited, distance, Dist_list)
Taka = Dist_list

Dist_list = [0 for _ in range(n)]
Visited = [False for _ in range(n)]
distance = 0
tree_distance(Adj_dict, v, Visited, distance, Dist_list)
Aoki = Dist_list

ans = 10**10
Taka_num = 0
node = 0
for i in range(n):
    if Aoki[i] >= Taka[i]:
        if Taka[i] >= Taka_num:
            Taka_num = Taka[i]
            node = i

# TakahashiはTaka_numのnodeへ逃げる
ans = Aoki[node] -1

print(ans)

Submission status: Runtime Error

Solution code:
def dps(no, fno, d, hen, D, MD, P):
    D[no] = d
    P[no] = fno
    maxd = d
    for h in hen[no]:
        if h == fno:
            continue
        maxd = max(maxd, dps(h, no, d + 1, hen, D, MD, P))
    MD[no] = maxd
    return maxd


def main():
    N, u, v = map(int, input().split())
    hen = {}
    for i in range(N - 1):
        A, B = map(int, input().split())
        if A in hen.keys():
            hen[A].append(B)
        else:
            hen[A] = [B]
        if B in hen.keys():
            hen[B].append(A)
        else:
            hen[B] = [A]
    DEPTH = [-1 for i in range(N + 1)]
    MAX_DEPTH = [-1 for i in range(N + 1)]
    Parent = [-1 for i in range(N + 1)]
    dps(v, -1, 0, hen, DEPTH, MAX_DEPTH, Parent)
    ans = DEPTH[u]
    p = u
    for i in range((DEPTH[u] + 1) // 2):
        p = Parent[p]
        ans = max(ans, MAX_DEPTH[p])
    print(ans - 1)

if __name__ == '__main__':
    main()

Submission status: Runtime Error

Solution code:
#!python3

def resolve():
    N, u, v = map(int, input().rstrip().split())
    N1 = N + 1

    d = [[] for _ in range(1, N1)]
    for i in range(1, N):
        a, b = map(int, input().rstrip().split())

        d[a].append(b)
        d[b].append(a)

    from collections import deque

    def f(x):
        q = deque()
        q.append(x)
        X = [-1] * N1

        while q:
            x = q.popleft()
            for i in d[x]:
                if X[i] == -1:
                    X[i] = X[x] + 1
                    q.append(i)
        return q

    U = f(u)
    V = f(v)

    m = 0
    for uu, vv in zip(U, V):
        if uu < vv:
            if vv > m:
                m = vv
    print(m-1)

if __name__ == "__main__":
    resolve()

Submission status: Runtime Error

Solution code:
#!/usr/bin/python3
import sys
import resource

sys.setrecursionlimit(10 ** 5)
resource.setrlimit(resource.RLIMIT_STACK, (-1, -1))

def search(n, total, dic):
    if dic[n] >= 0:
        return
    else:
        dic[n] = total
    for i in br[n]:
        search(i, total + 1, dic)

n, u, v = map(int, input().split())
br = {}
disu = {}
disv = {}
for i in range(n):
    br[i + 1] = []
    disu[i + 1] = -1
    disv[i + 1] = -1
for i in range(n - 1):
    a, b = map(int, input().split())
    br[a].append(b)
    br[b].append(a)

search(u, 0, disu)
search(v, 0, disv)
far = 0
for i in range(1, n + 1):
    if disv[i] < disu[i]:
        continue
    else:
        far = max(far, disv[i])

print(far - 1)

Submission status: Runtime Error

Solution code:
#!/usr/bin/python3

def search(n, total, dic):
    if dic[n] >= 0:
        return
    else:
        dic[n] = total
    for i in br[n]:
        search(i, total + 1, dic)

n, u, v = map(int, input().split())
br = {}
disu = {}
disv = {}
for i in range(n):
    br[i + 1] = []
    disu[i + 1] = -1
    disv[i + 1] = -1
for i in range(n - 1):
    a, b = map(int, input().split())
    br[a].append(b)
    br[b].append(a)

search(u, 0, disu)
search(v, 0, disv)
far = 0
for i in range(1, n + 1):
    if disv[i] < disu[i]:
        continue
    else:
        far = max(far, disv[i])

print(far - 1)

Submission status: Runtime Error

Solution code:
#!/usr/bin/python3

def search(n, total, dic):
    if dic[n] >= 0:
        return
    else:
        dic[n] = total
    for i in br[n]:
        search(i, total + 1, dic)

n, u, v = map(int, input().split())
br = {}
disu = {}
disv = {}
for i in range(n):
    br[i + 1] = []
    disu[i + 1] = -1
    disv[i + 1] = -1
for i in range(n - 1):
    a, b = map(int, input().split())
    br[a].append(b)
    br[b].append(a)

search(u, 0, disu)
search(v, 0, disv)
far = 0
for i in range(1, n + 1):
    if disv[i] < disu[i]:
        next
    else:
        far = max(far, disv[i])

print(far - 1)

Submission status: Runtime Error

Solution code:
#include <bits/stdc++.h>
#ifdef LOCAL_DEBUG
#define DEBUG 1
#define CERR if(DEBUG) cerr
#define MACRO(_1,_2,_3,_4,_5,_6,_7,_8,_9,_10,NAME,...) NAME
#define pr(...) CERR<<MACRO(__VA_ARGS__,pr10,pr9,pr8,pr7,pr6,pr5,pr4,pr3,pr2,pr1)(__VA_ARGS__)<<endl
#define pr1(a) (#a)<<"="<<(a)<<" "
#define pr2(a,b) pr1(a)<<pr1(b)
#define pr3(a,b,c) pr1(a)<<pr2(b,c)
#define pr4(a,b,c,d) pr1(a)<<pr3(b,c,d)
#define pr5(a,b,c,d,e) pr1(a)<<pr4(b,c,d,e)
#define pr6(a,b,c,d,e,f) pr1(a)<<pr5(b,c,d,e,f)
#define pr7(a,b,c,d,e,f,g) pr1(a)<<pr6(b,c,d,e,f,g)
#define pr8(a,b,c,d,e,f,g,h) pr1(a)<<pr7(b,c,d,e,f,g,h)
#define pr9(a,b,c,d,e,f,g,h,i) pr1(a)<<pr8(b,c,d,e,f,g,h,i)
#define pr10(a,b,c,d,e,f,g,h,i,j) pr1(a)<<pr9(b,c,d,e,f,g,h,i,j)
#define prArr(a){CERR<<(#a)<<"={";int i=0;for(auto t:(a))CERR<<(i++?", ":"")<<t;CERR<<"}"<<endl;}
#else
#define DEBUG 0
#define pr(...)
#define prArr(a)
#endif
using namespace std;
using Int = long long;
using _int = int;
using ll = long long;
using Double = long double;
const Int INF = (1LL<<60)+1e9; // ~ 1.15 * 1e18
const Int mod = (1e9)+7;
const Double EPS = 1e-8;
const Double PI = 6.0 * asin((Double)0.5);
using P = pair<Int,Int>;
template<class T> T Max(T &a,T b){return a=max(a,b);}
template<class T> T Min(T &a,T b){return a=min(a,b);}
template<class T1, class T2> ostream& operator<<(ostream& o,pair<T1,T2> p){return o<<"("<<p.first<<","<<p.second<<")";}
template<class T1, class T2, class T3> ostream& operator<<(ostream& o,tuple<T1,T2,T3> t){return o<<"("<<get<0>(t)<<","<<get<1>(t)<<","<<get<2>(t)<<")";}
template<class T1, class T2> istream& operator>>(istream& i,pair<T1,T2> &p){return i>>p.first>>p.second;}
template<class T> ostream& operator<<(ostream& o,vector<T> a){Int i=0;for(T t:a)o<<(i++?" ":"")<<t;return o;}
template<class T> istream& operator>>(istream& i,vector<T> &a){for(T &t:a)i>>t;return i;}
//INSERT ABOVE HERE
class LCA{
public:
  typedef pair<int,int> P;
  int LOG_V=20;                       //log V (自分で決めて)
  int V;                              //言わずもがな頂点数
  vector<vector<P> > G;               //グラフの隣接リストの表現
  int root;                           //根のノード番号
  vector<vector<int> > parent;        //親を2^k回辿って到達する頂点(根を通りすぎる場合は-1とする)
  vector<int> depth;                  //根からの深さ
  vector<int> D;                      //根からの距離
  int ok;

  LCA():V(-1){}
  LCA(int V,int root = 0)
    :V(V),G(V),root(root),parent(LOG_V,vector<int>(V)),depth(V), D(V,0),ok(0){}

  void add_edge(int a, int b,int c = 1){
    assert(a >= 0 && b >= 0);
    assert(a < V && b < V);
    G[a].push_back(P(b,c));
    G[b].push_back(P(a,c));
  }

  void dfs(int v,int p,int d,int c){
    assert(v < V);
    parent[0][v] = p;
    depth[v] = d;
    D[v] = c;
    for(auto to:G[v])
      if(to.first != p) dfs(to.first, v, d+1, c + to.second);
  }

  //vからn個上の祖先
  int getAnc(int v,int n){
    for(int k=0; k<LOG_V ;k++) if((v != -1) && (n>>k&1)) v=parent[k][v];
    return v;
  }

  //初期化
  void build(){
    ok = 1;
    //parent[0]とdepthを初期化する。
    dfs(root,-1,0,0);
    //parentを初期化する
    for(int k=0; k+1<LOG_V ;k++)
      for(int v=0; v<V ;v++)
        if(parent[k][v] < 0)parent[k+1][v] = -1;
        else parent[k+1][v] = parent[k][parent[k][v]];
  }

  //uとvのLCAを求める
  int lca(int u,int v){
    assert(ok);
    assert(u >= 0 && v >= 0);
    assert(u < V && v < V);
    if(depth[u]>depth[v]) swap(u,v);
    v = getAnc(v, depth[v] - depth[u]);

    if(u==v) return u;
    //二分探索でLCAを求める
    for(int k=LOG_V-1; k>=0 ;k--)
      if(parent[k][u] != parent[k][v]){
        u = parent[k][u];
        v = parent[k][v];
      }
    return parent[0][u];
  }

  int getDis(int u,int v){
    assert(u >= 0 && v >= 0);
    assert(u < V && v < V);
    return D[u] + D[v] - 2 * D[lca(u, v)];
  }
};

signed main(){
  srand((unsigned)time(NULL));
  cin.tie(0);
  ios_base::sync_with_stdio(0);
  cout << fixed << setprecision(12);

  int N, u, v;
  cin>>N>>u>>v; u--, v--;

  LCA lca(N, v);
  vector<vector<int> > G(N);
  for(int i=0;i<N-1;i++){
    int a, b;
    cin>>a>>b; a--, b--;
    lca.add_edge(a, b);
    G[a].push_back(b);
    G[b].push_back(a);
  }

  lca.build();

  int ans = 0;
  for(int i=0;i<N;i++){
    int m = lca.lca(u, i);
    int disU = lca.getDis(m, u);
    int disV = lca.getDis(m, v);
    if(disU >= disV) continue;
    Max(ans, lca.getDis(v, i) - 1);
  }

  cout<<ans<<endl;


  return 0;
}

Submission status: Runtime Error

Solution code:
from collections import deque
N,ppl,oni = map(int,input().split())
ppl -= 1
oni -= 1
AB = [ []for i in range(N)]
for i in range(N-1):
    a,b = map(int,input().split())
    AB[a-1].append(b-1)
    AB[b-1].append(a-1)

def dfs(start):
    dist = [-1 for i in range(N)]
    dist[start] = 0
    que = deque()
    que.append(start)
    while que:
        q = que.popleft()
        for nextr in AB[q]:
            if dist[nextr] == -1:
                dist[nextr] = dist[q] +1
                que.append(nextr)
    return dist
    
if len(AB[ppl]) == 1 and oni in AB[ppl]:
    print(0)
else:
    ppldist = dfs(ppl)
    onidist = dfs(oni)
    maxa = max(onidist)
    for i in range(max(onidist),-1,-1):
        for j in [k for k in range(len(onidist)) if onidist[k] == maxa]:
            if maxa >= ppldist[j]:
                if maxa&ppldist[j] == 1:
                    ans = maxa
                else:
                    ans = maxa-1
    print(ans)

Submission status: Runtime Error

Solution code:
import queue
N,u,v = map(int,input().split())
u -= 1
v -= 1
E = [[] for _ in range(N)]
for _ in range(N-1):
    A,B=map(int,input().split())
    E[A-1].append(B-1)
    E[B-1].append(A-1)

ans = 0
if u==v:
    print(0)
    exit()

#u〜vの最短経路を求める
r = []
used = [False]*N
def dfs(i,end):
    global r
    used[i] = True
    if i==end:
        r.append(i)
        return True
    for e in E[i]:
        if not used[e]:
            if dfs(e,end):
                r.append(i)
                return True
    return False
dfs(v,u)

ans += (len(r)//2)+(len(r)&1)
v = r[len(r)//2]
u = r[(len(r)//2)-1]

#uから最も遠い頂点までの距離を求める
dmax = 0
used = [False]*N
def dfs2(i,end,d):
    global dmax
    used[i] = True
    if i==end:
        return
    dmax = max(dmax,d)
    for e in E[i]:
        if not used[e]:
            dfs2(e,end,d+1)
dfs2(u,v,0)
ans += dmax - 1

print(ans)

Submission status: Runtime Error

Solution code:
# 解説を見た

def solve(N, t, a, g) -> int:
    def calc_dist(init):
        dist = [-1] * N
        dist[init] = 0

        def _calc_dist(curr):
            for next_ in g[curr]:
                if dist[next_] != -1:
                    continue
                dist[next_] = dist[curr] + 1
                _calc_dist(next_)

        _calc_dist(init)
        return dist

    dist_a = calc_dist(a)
    dist_t = calc_dist(t)

    return max(dist_a[v] for v in range(N) if dist_t[v] < dist_a[v]) - 1


if __name__ == '__main__':
    N, t, a = map(int, input().split())
    t -= 1
    a -= 1

    g = tuple(set() for _ in range(N))
    for _ in range(N - 1):
        u, v = (int(x) - 1 for x in input().split())
        g[u].add(v)
        g[v].add(u)

    print(solve(N, t, a, g))

# 青木君からの距離 > 高橋君からの距離 となる頂点Xが目的地の候補
# 青木君と高橋君の共通祖先からの距離は等しいので、
# 共通祖先への距離は、 青木君 > 高橋君 となり、高橋君は必ずXに到達できる
# Xに着いた高橋君は、手前の頂点とXとを行ったり来たりする
# a-t->at-: aが一歩進んだときに高橋君に会う(-は無人のマス目)
# at: tが手前の頂点に移動したときに青木君に会う
# いずれも手前の頂点まで青木君が移動したときにゲームが終わる
# どのXを選んでも、Xの手前でゲームが終わるので、青木君から最も遠いXを選ぶのが最善
# 頂点X: 追いつめられる位置=葉

Submission status: Runtime Error

Solution code:
import sys

stdin = sys.stdin
ns = lambda: stdin.readline().rstrip()
na = lambda: list(map(int, stdin.readline().split()))
ni = lambda: int(ns())

(n,u,v)=na()
u -= 1
v -= 1

g = [[] for _ in range(n)]

for i in range(0, n-1):
    (a, b) = na()
    g[a-1].append(b-1)
    g[b-1].append(a-1)


dep1 = [0] * n
dep2 = [0] * n
def dfs(now, pre, d, dep):
    dep[now] = d
    for nex in g[now]:
        if pre == nex:
            continue
        dfs(nex,now,d+1,dep)


dfs(u, -1, 0, dep1)
dfs(v, -1, 0, dep2)

ret = 0
for i in range(n):
    if dep1[i] < dep2[i]:
        ret = max(ret, dep2[i]-1)
print(ret)

Submission status: Runtime Error

Solution code:
n,u,v = map(int,input().split())
edge = [[] for i in range(n+1)]
distt = [0 for i in range(n+1)]
dista = [0 for i in range(n+1)]

for i in range(n-1):
    a, b = map(int, input().split())
    edge[a].append(b)
    edge[b].append(a)

def tdfs(x, last = -1):
    for to in edge[x]:
        if(to == last):continue
        distt[to] = distt[x] + 1
        tdfs(to, x)

def adfs(x, last = -1):
    for to in edge[x]:
        if(to == last):continue
        dista[to] = dista[x] + 1
        adfs(to, x)

tdfs(u)
adfs(v)
ans = 0

for i in range(1, n+1):
    if distt[i] >= dista[i]:continue
    l = distt[i]
    k = dista[i] - distt[i]
    ans = max(ans, k - 1 + l)

print(ans)

Submission status: Runtime Error

Solution code:
import sys
from collections import deque
sys.setrecursionlimit = 10 ** 5
input = sys.stdin.readline
N, u, v = [int(x) for x in input().strip().split()]

m = [[] for n in range(N)]
f_aokikun = [False for n in range(N)]
f_takahashikun = [False for n in range(N)]
aokikun = [0 for n in range(N)]
takahashikun = [0 for n in range(N)]
takahashikun_enable = [1 for n in range(N)]
for n in range(N-1):
    a, b = [int(x) for x in input().strip().split()]
    m[a-1].append(b)
    m[b-1].append(a)

def aokifunc(c, f, p, cost):
    c[p-1] = cost
    f[p-1] = True
    for p_next in m[p-1]:
        if f[p_next-1]:
            continue
        aokifunc(c, f, p_next, cost+1)

def takahashifunc(c, f, p, cost, aokikun, takahashikun_enable):
    if aokikun[p-1] <= cost:
        takahashikun_enable[p-1] = 0
    c[p-1] = 0
    f[p-1] = True
    for p_next in m[p-1]:
        if f[p_next-1]:
            continue
        takahashifunc(c, f, p_next, cost+1, aokikun, takahashikun_enable)

aokifunc(aokikun, f_aokikun, v, 0)
takahashifunc(takahashikun, f_takahashikun, u, 0, aokikun, takahashikun_enable)
print(max([i * j for i, j in zip(aokikun, takahashikun_enable)])-1)