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: Time Limit Exceeded

Solution code:
import sys
sys.setrecursionlimit(1000000)
N, u, v = map(int, input().split())
u -= 1
v -= 1

G = [[] for _ in range(N)]
elens = [0] * N

for _ in range(N - 1):
    a, b = map(int, input().split())
    a -= 1
    b -= 1
    G[a].append(b)
    G[b].append(a)
    elens[a] += 1
    elens[b] += 1
depths = [0] * N
dists = [0] * N


TAKAHASHI = [0] * N
AOKI = [0] * N

def dfs_aoki(cur: int, past: int, d: int):
    AOKI[cur] = d

    for nx in G[cur]:
        if nx == past:
            continue
        dfs_aoki(nx, cur, d + 1)

def dfs_takahashi(cur: int, past: int, d: int):
    TAKAHASHI[cur] = d

    for nx in G[cur]:
        if nx == past:
            continue
        dfs_takahashi(nx, cur, d + 1)

dfs_takahashi(u, -1, 0)
dfs_aoki(v, -1, 0)

ans = 0

for i in range(N):
    if TAKAHASHI[i] < AOKI[i]:
        ans = max(ans, AOKI[i] - 1)

print(ans)

Submission status: Time Limit Exceeded

Solution code:
#隣接リスト作成テンプレ
N,u,v=list(map(int,input().split()))#N:ノード数
#隣接リスト作成
A={}
for i in range(N):
    A[i+1]=[]
#print(A)

#隣接リストデータインプット
for i in range(N-1):
    a,b=list(map(int,input().split()))
    A[a].append(b)
    A[b].append(a)
#print(A)

#print(u,v)

#Bからpに関わる連結を削除する
def del_connect(p,B):
    B[p] = []
    for i in B:
        if p in B[i]:
            B[i].remove(p)#ここでAも変化してしまう←対処
    
#ダイクストラ法による２点間の距離算出関数
def distance(a,b):
    #print("-- {},{}".format(a,b))
    dist = 0
    B = {}
    for i in A:
        B[i] = A[i].copy()
    #今いる点リスト
    p_list = [a]
    #移動後の点リスト
    q_list = []
    while b not in p_list:
        for i in p_list:#今いる点全てについて
            for j in B[i]:#次に行ける点を全て調べ
                q_list.append(j)#q_listにリストアップする
        #print("q_list",q_list)
        #今いる点に関わる連結をBから削除する
        for i in p_list:
            del_connect(i,B)
        #次に行ける点に移動する
        p_list = q_list.copy()
        #print("p_list:",p_list)
        q_list = []
        dist += 1
        
        #print("A",A)
    #print("c={}".format(dist))
    return dist

#print("A",A)
#まず、葉をリストアップする
leaves = []
for i in A:
    if len(A[i]) == 1:
        leaves.append(i)
#print("Leaves are",leaves)
#print("u",u,"v",v)

#u:逃げ（先）、v:鬼(後)
d = 0
for l in leaves:
    #print("---- l={}".format(l))
    u_dist = distance(u,l)
    v_dist = distance(v,l)

    if u_dist < v_dist and v_dist > d:#葉の中で逃げが先に到達でき、且つ最大のものを求める。
        d = v_dist
    #print("l={}.d={}".format(l,d))
#print("d",d)
    
print(d-1)

Submission status: Time Limit Exceeded

Solution code:
import sys
import math
MAX_INT = int(10e15)
MIN_INT = -MAX_INT
mod = 1000000007
sys.setrecursionlimit(1000000)
def IL(): return list(map(int,input().split()))
def SL(): return input().split()
def I(): return int(sys.stdin.readline())
def S(): return input()

def tami(n, cnt, aoki, aoki_visited, edge):
  aoki_visited[n] = True
  aoki[n] = cnt
  for x in edge[n]:
    if aoki_visited[x] == False:
      tami(x, cnt+1, aoki, aoki_visited, edge)

def tami2(n, cnt, choku, choku_visited, edge, aoki):
  choku_visited[n] = True
  if cnt <= aoki[n]:
    choku[n] = cnt
    for x in edge[n]:
      if choku_visited[x] == False:
        tami2(x, cnt+1, choku, choku_visited, edge, aoki)


def main():
  N, u, v = IL()
  ab = [IL() for _ in range(N-1)]

  aoki = [0]*(N+1)
  aoki_visited = [False]*(N+1)
  choku = [0]*(N+1)
  choku_visited = [False]*(N+1)

  edge = [[] for _ in range(N+1)]
  for a,b in ab:
    edge[a].append(b)
    edge[b].append(a)

  ans = 0
  tami(v, 0, aoki, aoki_visited, edge)
  tami2(u, 0, choku, choku_visited, edge, aoki)
  #print(aoki)
  #print(choku)

  for i in range(N+1):
    if choku[i] == 0 and i != u:
      continue
    if aoki[i] > choku[i]:
      ans = max(ans, aoki[i] - 1)

  print(ans)

main()

Submission status: Time Limit Exceeded

Solution code:
import sys
import math
MAX_INT = int(10e15)
MIN_INT = -MAX_INT
mod = 1000000007
sys.setrecursionlimit(1000000)
def IL(): return list(map(int,input().split()))
def SL(): return input().split()
def I(): return int(sys.stdin.readline())
def S(): return input()

def tami(n, cnt, aoki, aoki_visited):
  aoki_visited[n] = True
  aoki[n] = cnt
  for x in edge[n]:
    if aoki_visited[x] == False:
      tami(x, cnt+1, aoki, aoki_visited)

def tami2(n, cnt, choku, choku_visited):
  choku_visited[n] = True
  if cnt <= aoki[n]:
    choku[n] = cnt
    for x in edge[n]:
      if choku_visited[x] == False:
        tami2(x, cnt+1, choku, choku_visited)

N, u, v = IL()
ab = [IL() for _ in range(N-1)]

aoki = [0]*(N+1)
aoki_visited = [False]*(N+1)
choku = [0]*(N+1)
choku_visited = [False]*(N+1)

edge = [[] for _ in range(N+1)]
for a,b in ab:
  edge[a].append(b)
  edge[b].append(a)

ans = 0
tami(v, 0, aoki, aoki_visited)
tami2(u, 0, choku, choku_visited)
#print(aoki)
#print(choku)

for i in range(N+1):
  if choku[i] == 0 and i != u:
    continue
  if aoki[i] > choku[i]:
    ans = max(ans, aoki[i] - 1)

print(ans)

Submission status: Time Limit Exceeded

Solution code:
import sys
import math
MAX_INT = int(10e15)
MIN_INT = -MAX_INT
mod = 1000000007
sys.setrecursionlimit(1000000)
def IL(): return list(map(int,input().split()))
def SL(): return input().split()
def I(): return int(sys.stdin.readline())
def S(): return input()

def tami(n, cnt):
  aoki_visited[n] = True
  aoki[n] = cnt
  for x in edge[n]:
    if aoki_visited[x] == False:
      tami(x, cnt+1)

def tami2(n, cnt):
  choku_visited[n] = True
  if cnt <= aoki[n]:
    choku[n] = cnt
    for x in edge[n]:
      if choku_visited[x] == False:
        tami2(x, cnt+1)

N, u, v = IL()
ab = [IL() for _ in range(N-1)]

aoki = [0]*(N+1)
aoki_visited = [False]*(N+1)
choku = [0]*(N+1)
choku_visited = [False]*(N+1)

edge = [[] for _ in range(N+1)]
for a,b in ab:
  edge[a].append(b)
  edge[b].append(a)

ans = 0
tami(v, 0)
tami2(u, 0)
#print(aoki)
#print(choku)

for i in range(N+1):
  if choku[i] == 0 and i != u:
    continue
  if aoki[i] > choku[i]:
    ans = max(ans, aoki[i] - 1)

print(ans)

Submission status: Time Limit Exceeded

Solution code:
def calc_destination(start, edges, N):
    destination = [-1] * (N + 1)
    destination[start] = 0
    q = [start]
    while len(q) != 0:
        current = q.pop(0)
        for n in edges[current]:
            if destination[n] != -1:
                continue
            destination[n] = destination[current] + 1
            q.append(n)
    return destination

def main():
    N, u, v = map(int, input().split())

    if u == v:
        print(0)
        return

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

    tak = calc_destination(u, edges, N)
    aok = calc_destination(v, edges, N)

    result = 0
    for i in range(1, N + 1):
        aoki = aok[i]
        if tak[i] >= aoki:
            continue
        if aoki > result:
            result = aoki
    print(result - 1)

main()

Submission status: Time Limit Exceeded

Solution code:
from sys import exit

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

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

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


def calc_destination(start, edges):
    destination = [-1] * (N + 1)
    destination[start] = 0
    q = [start]
    while len(q) != 0:
        current = q.pop(0)
        for n in edges[current]:
            if destination[n] != -1:
                continue
            destination[n] = destination[current] + 1
            q.append(n)
    return destination


tak = calc_destination(u, edges)
aok = calc_destination(v, edges)

result = 0
for i in range(1, N + 1):
    aoki = aok[i]
    if tak[i] >= aoki:
        continue
    if aoki > result:
        result = aoki
print(result - 1)

Submission status: Time Limit Exceeded

Solution code:
def main():
    N, u, v = (int(i) for i in input().split())
    G = [[] for _ in range(N)]
    for i in range(N-1):
        a, b = (int(i) for i in input().split())
        G[a-1].append(b-1)
        G[b-1].append(a-1)

    d_from_u = [-1] * N
    d_from_v = [-1] * N

    def dfs(v, d):
        todo = []
        d[v] = 0
        todo.append(v)
        while todo:
            u = todo[-1]
            for next_v in G[u]:
                if 0 <= d[next_v]:
                    continue
                d[next_v] = d[u] + 1
                todo.append(next_v)
                break
            else:
                todo.pop()

    u, v = u-1, v-1
    dfs(u, d_from_u)
    dfs(v, d_from_v)
    ans = 0
    for du, dv in zip(d_from_u, d_from_v):
        if du < dv and ans < dv - 1:
            ans = dv - 1
    print(ans)


if __name__ == '__main__':
    main()

Submission status: Time Limit Exceeded

Solution code:
def main():
    N, u, v = (int(i) for i in input().split())
    G = [[] for _ in range(N)]
    for i in range(N-1):
        a, b = (int(i) for i in input().split())
        G[a-1].append(b-1)
        G[b-1].append(a-1)

    d_from_u = [(1 << 63)-1 for i in range(N)]
    d_from_v = [(1 << 63)-1 for i in range(N)]

    def dfs(v, d):
        seen = [False] * N
        todo = []
        seen[v] = True
        d[v] = 0
        todo.append(v)
        while todo:
            u = todo[-1]

            for next_v in G[u]:
                if seen[next_v]:
                    continue
                seen[next_v] = True
                d[next_v] = d[u] + 1
                todo.append(next_v)
                break
            else:
                todo.pop()

    u, v = u-1, v-1
    dfs(u, d_from_u)
    dfs(v, d_from_v)
    ans = 0
    for du, dv in zip(d_from_u, d_from_v):
        if du < dv and ans < dv - 1:
            ans = dv - 1
    print(ans)


if __name__ == '__main__':
    main()

Submission status: Time Limit Exceeded

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

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


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: Time Limit Exceeded

Solution code:
import sys
sys.setrecursionlimit(1000000)
N, u, v = map(int, input().split())
u -= 1
v -= 1

G = [[] for _ in range(N)]
elens = [0] * N

for _ in range(N - 1):
    a, b = map(int, input().split())
    a -= 1
    b -= 1
    G[a].append(b)
    G[b].append(a)
    elens[a] += 1
    elens[b] += 1
depths = [0] * N
dists = [0] * N

def dfs(cur: int, past: int, d: int, ds):
    ds[cur] = d

    for nx in G[cur]:
        if nx == past:
            continue
        dfs(nx, cur, d + 1, ds)

TAKAHASHI = [0] * N
AOKI = [0] * N

dfs(u, -1, 0, TAKAHASHI)
dfs(v, -1, 0, AOKI)

ans = 0

for i in range(N):
    if TAKAHASHI[i] < AOKI[i]:
        ans = max(ans, AOKI[i] - 1)

print(ans)

Submission status: Time Limit Exceeded

Solution code:
N, u, v = map(int, input().split())
u, v = u-1, v-1
adjL = [set() for _ in range(N)]
for _ in range(N-1):
    A, B = map(int, input().split())
    A, B = A-1, B-1
    adjL[A].add(B)
    adjL[B].add(A)

ans = 0
v1s = set([u])
v2s = set([v])
useds = [False] * N
useds[v] = True
while True:
    vs = set()
    for v1 in v1s:
        vs |= adjL[v1]
    v1s = vs
    v1s -= v2s
    if not v1s: break

    ans += 1
    vs = set()
    for v2 in v2s:
        vs |= adjL[v2]
    v2s = set([v for v in vs if not useds[v]])
    for v2 in v2s:
        useds[v2] = True
    v1s -= v2s
    if not v1s: break

print(ans)

Submission status: Time Limit Exceeded

Solution code:
N, u, v = map(int, input().split())
u, v = u-1, v-1
AB = [list(map(int, input().split())) for a in range(N-1)]

G = [[0 for b in range(N)] for a in range(N)]
D = [[0 for b in range(N)] for a in range(N)]

for ab in AB:
  G[ab[0]-1][ab[1]-1] = 1
  G[ab[1]-1][ab[0]-1] = 1

def dfs(current, goal, distance, prev):
  if current == goal:
    return distance
  if 0 < D[current][goal] :
    return D[current][goal]
  if 0 < D[goal][current] :
    return D[goal][current]
  dists = [0]
  for i in range(N):
    if G[current][i] == 1 and i != prev and i != current:
      dists.append(dfs(i, goal, distance + 1, current))
  D[goal][current] = max(dists)
  D[current][goal] = D[goal][current]
  return D[current][goal]

distances = [0]
for i in range(N):
  count = 0
  for j in range(N):
    if G[i][j] == 1:
      count += 1
  if count == 1:
    aoki = dfs(i, v, 0, -1)
    takahashi = dfs(i, u, 0, -1)
    if aoki > takahashi:
      distances.append(dfs(i, v, 0, -1))

print(max(distances)-1)

Submission status: Time Limit Exceeded

Solution code:
N, u, v = map(int, input().split())
u, v = u-1, v-1
AB = [list(map(int, input().split())) for a in range(N-1)]

G = [[0 for b in range(N)] for a in range(N)]

for ab in AB:
  G[ab[0]-1][ab[1]-1] = 1
  G[ab[1]-1][ab[0]-1] = 1

def dfs(current, goal, distance, prev):
  if current == goal:
    return distance
  dists = [0]
  for i in range(N):
    if G[current][i] == 1 and i != prev and i != current:
      dists.append(dfs(i, goal, distance + 1, current))
  return max(dists)

distances = [0]
for i in range(N):
  count = 0
  for j in range(N):
    if G[i][j] == 1:
      count += 1
  if count == 1:
    distances.append(dfs(i, v, 0, -1))

print(max(distances)-1)

Submission status: Time Limit Exceeded

Solution code:
import sys
sys.setrecursionlimit(1000000)
N, u, v = map(int, input().split())
u -= 1
v -= 1

G = [[] for _ in range(N)]
elens = [0] * N

for _ in range(N - 1):
    a, b = map(int, input().split())
    a -= 1
    b -= 1
    G[a].append(b)
    G[b].append(a)
    elens[a] += 1
    elens[b] += 1

def dfs_aoki(cur: int, past: int, d: int):

    if elens[cur] == 1 and G[cur][0] == past:
        return [d - 1, 0 if cur == u else -1]

    ret = 0
    takahashi_d = -1

    for nx in G[cur]:
        if nx == past:
            continue

        r = dfs_aoki(nx, cur, d + 1)
        depth, td = r[0], r[1]
        if td >= 0:
            if td >= 0 and d <= td + 1:
                return depth, td
            takahashi_d = td + 1

        ret = max(ret, depth)

    return [ret, takahashi_d]

ret = dfs_aoki(v, -1, 0)
print(ret[0])

Submission status: Time Limit Exceeded

Solution code:
import sys
sys.setrecursionlimit(1000000)
N, u, v = map(int, input().split())
u -= 1
v -= 1

G = [[] for _ in range(N)]
elens = [0] * N

for _ in range(N - 1):
    a, b = map(int, input().split())
    a -= 1
    b -= 1
    G[a].append(b)
    G[b].append(a)
    elens[a] += 1
    elens[b] += 1

def dfs_aoki(cur: int, past: int, G, d: int):

    if elens[cur] == 1 and G[cur][0] == past:
        return d - 1, 0 if cur == u else -1

    ret = 0
    takahashi_d = -1

    for nx in G[cur]:
        if nx == past:
            continue

        depth, td = dfs_aoki(nx, cur, G, d + 1)
        if td >= 0:
            if td >= 0 and d <= td + 1:
                return depth, td
            takahashi_d = td + 1

        ret = max(ret, depth)

    return ret, takahashi_d

d, _ = dfs_aoki(v, -1, G, 0)
print(d)

Submission status: Time Limit Exceeded

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

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

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

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

    stack1 = [u-1]
    stack2 = [v-1]

    dis1 = [-1] * n
    dis2 = [-1] * n
    dis1[u-1] = 0
    dis2[v-1] = 0

    count = 0

    while stack1 or stack2:
        count += 1
        for _ in range(len(stack1)):
            q1 = stack1.pop(0)
            for i in edges[q1]:
                if dis1[i] == -1 and dis2[i] == -1:
                    dis1[i] = count
                    stack1.append(i)

        for _ in range(len(stack2)):
            q2 = stack2.pop(0)
            for i in edges[q2]:
                if dis2[i] == -1:
                    dis2[i] = count
                    stack2.append(i)

    ans = 0
    for i in range(n):
        if dis1[i] != -1:
            ans = max(ans, dis2[i])

    print(ans-1)

if __name__ == '__main__':
    main()

Submission status: Time Limit Exceeded

Solution code:
import sys
sys.setrecursionlimit(1000000)
N, u, v = map(int, input().split())
u -= 1
v -= 1

G = [[] for _ in range(N)]
elens = [0] * N

for _ in range(N - 1):
    a, b = map(int, input().split())
    a -= 1
    b -= 1
    G[a].append(b)
    G[b].append(a)
    elens[a] += 1
    elens[b] += 1


TAKAHASHI = [0] * N

def dfs_takahashi(cur: int, past: int, G, d: int):
    TAKAHASHI[cur] = d

    for nx in G[cur]:
        if nx == past:
            continue
        dfs_takahashi(nx, cur, G, d + 1)

def dfs_aoki(cur: int, past: int, G, d: int):

    if elens[cur] == 1 and G[cur][0] == past:
        return d - 1, cur == u

    ret = 0
    ret_te = cur == u

    for nx in G[cur]:
        if nx == past:
            continue

        depth, takahashi_exists = dfs_aoki(nx, cur, G, d + 1)
        if takahashi_exists and d <= TAKAHASHI[cur]:
            return depth, True

        ret = max(ret, depth)
        ret_te |= takahashi_exists

    return ret, ret_te

dfs_takahashi(u, -1, G, 0)
d, _ = dfs_aoki(v, -1, G, 0)
print(d)

Submission status: Time Limit Exceeded

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

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

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

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

    stack1 = [u-1]
    stack2 = [v-1]

    dis1 = [-1] * n
    dis2 = [-1] * n
    dis1[u-1] = 0
    dis2[v-1] = 0

    while stack1 or stack2:
        for _ in range(len(stack1)):
            q1 = stack1.pop(0)
            for i in edges[q1]:
                if dis1[i] == -1 and dis2[i] == -1:
                    dis1[i] = dis1[q1] + 1
                    stack1.append(i)

        for _ in range(len(stack2)):
            q2 = stack2.pop(0)
            for i in edges[q2]:
                if dis2[i] == -1:
                    dis2[i] = dis2[q2] + 1
                    stack2.append(i)

    ans = 0
    for i in range(n):
        if dis1[i] != -1:
            ans = max(ans, dis2[i])

    print(ans-1)

if __name__ == '__main__':
    main()

Submission status: Time Limit Exceeded

Solution code:
import sys
sys.setrecursionlimit(1000000)
 
N, u, v = map(int, input().split())
 
u -= 1
v -= 1
 
graph = [[] for i in range(N)]
for i in range(N - 1):
    a, b = map(int, input().split())
    a -= 1
    b -= 1
    graph[a].append(b)
    graph[b].append(a)
 
lst = []
def calcDist(cur, par, dst):
    global lst
    lst[cur] = dst
    for neighbour in graph[cur]:
        if neighbour == par: continue
        calcDist(neighbour, cur, dst + 1)
        
uDist = [None for i in range(N)]
vDist = [None for i in range(N)]
lst = uDist
calcDist(u, -1, 0)
lst = vDist
calcDist(v, -1, 0)
 
best = 0
 
for node in range(N):
    if uDist[node] < vDist[node]: best = max(best, vDist[node] - 1)
print(best)

Submission status: Time Limit Exceeded

Solution code:
import sys
sys.setrecursionlimit(1000000)
 
N, u, v = map(int, input().split())
 
u -= 1
v -= 1
 
graph = [[] for i in range(N)]
for i in range(N - 1):
    a, b = map(int, input().split())
    a -= 1
    b -= 1
    graph[a].append(b)
    graph[b].append(a)
 
lst = []
def calcDist(cur, par, dst):
    global lst
    lst[cur] = dst
    for neighbour in graph[cur]:
        if neighbour == par: continue
        calcDist(neighbour, cur, dst + 1)
        
uDist = [None for i in range(N)]
vDist = [None for i in range(N)]
lst = uDist
calcDist(u, -1, 0)
lst = vDist
calcDist(v, -1, 0)
 
best = 0

for node in range(N):
    if uDist[node] < vDist[node]: best = max(best, vDist[node] - 1)
print(best)

Submission status: Time Limit Exceeded

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

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

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

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

stack1 = [u-1]
stack2 = [v-1]

dis1 = [-1] * n
dis2 = [-1] * n
dis1[u-1] = 0
dis2[v-1] = 0

while stack1:
    for _ in range(len(stack1)):
        q1 = stack1.pop(0)
        for i in edges[q1]:
            if dis1[i] == -1 and dis2[i] == -1:
                dis1[i] = dis1[q1] + 1
                stack1.append(i)

    for _ in range(len(stack2)):
        q2 = stack2.pop(0)
        for i in edges[q2]:
            if dis2[i] == -1:
                dis2[i] = dis2[q2] + 1
                stack2.append(i)

while stack2:
    q = stack2.pop(0)
    for i in edges[q]:
        if dis2[i] == -1:
            dis2[i] = dis2[q] + 1
            stack2.append(i)

ans = 0
for i in range(n):
    if dis1[i] != -1:
        ans = max(ans, dis2[i])

print(ans-1)

Submission status: Time Limit Exceeded

Solution code:
import queue

INF = 1 << 30

s = [-1, -1]
n, s[0], s[1] = map(int, input().split())
s[0] -= 1
s[1] -= 1

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

cost = [[INF for j in range(n)] for i in range(2)]

for i in range(2):
    cost[i][s[i]] = 0
    que = queue.Queue(n)
    que.put(s[i])

    while not que.empty():
        now = que.get()
        for j in range(len(g[now])):
            if cost[i][g[now][j]] > cost[i][now] + 1:
                cost[i][g[now][j]] = cost[i][now] + 1
                que.put(g[now][j])

maxi = -1
maxdex = -1
for i in range(n):
    if len(g[i]) == 1 and maxi < cost[1][i] and cost[0][i] < cost[1][i]:
        maxi = cost[1][i]
        maxdex = i

dif = cost[1][maxdex] - cost[0][maxdex]

ans = cost[0][maxdex] + dif - 1
print(ans)

Submission status: Time Limit Exceeded

Solution code:
import sys
import math
from collections import deque
MAX_INT = int(10e15)
MIN_INT = -MAX_INT
mod = 1000000007
sys.setrecursionlimit(1000000)
def IL(): return list(map(int,input().split()))
def SL(): return input().split()
def I(): return int(sys.stdin.readline())
def S(): return input()

def tami2(n, cnt):
  if n == v:
    return
  choku_visited[n] = True
  if cnt <= aoki[n]:
    choku[n] = cnt
    for x in edge[n]:
      if choku_visited[x] == False:
        tami2(x, cnt+1)

N, u, v = IL()
ab = [IL() for _ in range(N-1)]

aoki = [0]*(N+1)
aoki_visited = [False]*(N+1)
choku = [0]*(N+1)
choku_visited = [False]*(N+1)

edge = [[] for _ in range(N+1)]
for a,b in ab:
  edge[a].append(b)
  edge[b].append(a)

d = deque([[v,0]])
while d:
  n,cnt = d.popleft()
  aoki_visited[n] = True
  aoki[n] = cnt
  for x in edge[n]:
    if aoki_visited[x] == False:
      d.append([x, cnt+1])

tami2(u, 0)
#print(aoki)
#print(choku)

ans = 0
for i in range(N+1):
  if choku[i] == 0 and i != u:
    continue
  if aoki[i] > choku[i]:
    ans = max(ans, aoki[i] - 1)

print(ans)

Submission status: Time Limit Exceeded

Solution code:
import sys
import math
MAX_INT = int(10e15)
MIN_INT = -MAX_INT
mod = 1000000007
sys.setrecursionlimit(1000000)
def IL(): return list(map(int,input().split()))
def SL(): return input().split()
def I(): return int(sys.stdin.readline())
def S(): return input()

def tami(n, cnt):
  aoki_visited[n] = True
  aoki[n] = cnt
  for x in edge[n]:
    if aoki_visited[x] == False:
      tami(x, cnt+1)

def tami2(n, cnt):
  choku_visited[n] = True
  if cnt <= aoki[n]:
    choku[n] = cnt
    for x in edge[n]:
      if choku_visited[x] == False:
        tami2(x, cnt+1)

N, u, v = IL()
ab = [IL() for _ in range(N-1)]

aoki = [0]*(N+1)
aoki_visited = [False]*(N+1)
choku = [0]*(N+1)
choku_visited = [False]*(N+1)

edge = [[] for _ in range(N+1)]
for a,b in ab:
  edge[a].append(b)
  edge[b].append(a)

ans = 0
aoki[v] = MAX_INT
tami(v, 0)
tami2(u, 0)
#print(aoki)
#print(choku)

for i in range(N+1):
  if choku[i] == 0 and i != u:
    continue
  if aoki[i] > choku[i]:
    ans = max(ans, aoki[i] - 1)

print(ans)

Submission status: Time Limit Exceeded

Solution code:
import sys
sys.setrecursionlimit(10**6)
input = sys.stdin.readline

n,u,v = map(int, input().split())
adjacent_list = [[] for i in range(n+1)]
aoki = [0 for i in range(n+1)]
takahashi = [0 for i in range(n+1)]
for i in range(n-1):
    a,b = map(int ,input().split())
    adjacent_list[a].append(b)
    adjacent_list[b].append(a)

def dfs(node, count,li):
    global node_par
    li[node] = count
    finished.add(node)
    for i in adjacent_list[node]:
        if i not in finished:
            node_par[i] = node
            dfs(i, count + 1,li)
        
node_par = [0 for i in range(n+1)]

finished = set()
dfs(u,0,takahashi)

#辿って親保存しとく
finished = set()
dfs(v,0,aoki)

#さかのぼれるとこまで行く,startがさかのぼれる最大のノーど
par = u
start = u
while takahashi[par] < aoki[par]:
    start = par
    par = node_par[start]

ans_height = [0 for i in range(n+1)]
finished = set([node_par[start]])
dfs(start,0,ans_height)
print(max(ans_height) + aoki[start] - 1)

Submission status: Time Limit Exceeded

Solution code:
import sys
sys.setrecursionlimit(10**6)
input = sys.stdin.readline

n,u,v = map(int, input().split())
adjacent_list = [[] for i in range(n+1)]
aoki = [0 for i in range(n+1)]
takahashi = [0 for i in range(n+1)]
for i in range(n-1):
    a,b = map(int ,input().split())
    adjacent_list[a].append(b)
    adjacent_list[b].append(a)

def dfs(node, count,li):
    li[node] = count
    finished.add(node)
    for i in adjacent_list[node]:
        if i not in finished:
            dfs(i, count + 1,li)
def dfs_par(node, count,li):
    global node_par
    li[node] = count
    finished.add(node)
    for i in adjacent_list[node]:
        if i not in finished:
            node_par[i] = node
            dfs_par(i, count + 1,li)
        
node_par = [0 for i in range(n+1)]

finished = set()
dfs(u,0,takahashi)

#辿って親保存しとく
finished = set()
dfs_par(v,0,aoki)

#さかのぼれるとこまで行く,startがさかのぼれる最大のノーど
par = u
start = u
while takahashi[par] < aoki[par]:
    start = par
    par = node_par[start]

ans_height = [0 for i in range(n+1)]
finished = set([node_par[start]])
dfs(start,0,ans_height)
print(max(ans_height) + aoki[start] - 1)

Submission status: Time Limit Exceeded

Solution code:
import sys
sys.setrecursionlimit(10**6)

n,u,v = map(int, input().split())
adjacent_list = [[] for i in range(n+1)]
aoki = [0 for i in range(n+1)]
takahashi = [0 for i in range(n+1)]
for i in range(n-1):
    a,b = map(int ,input().split())
    adjacent_list[a].append(b)
    adjacent_list[b].append(a)

def dfs(node, count,li):
    li[node] = count
    finished.add(node)
    for i in adjacent_list[node]:
        if i not in finished:
            dfs(i, count + 1,li)
def dfs_par(node, count,li):
    global node_par
    li[node] = count
    finished.add(node)
    for i in adjacent_list[node]:
        if i not in finished:
            node_par[i] = node
            dfs_par(i, count + 1,li)
        
node_par = [0 for i in range(n+1)]

finished = set()
dfs(u,0,takahashi)

#辿って親保存しとく
finished = set()
dfs_par(v,0,aoki)

#さかのぼれるとこまで行く,startがさかのぼれる最大のノーど
par = u
start = u
while takahashi[par] < aoki[par]:
    start = par
    par = node_par[start]

ans_height = [0 for i in range(n+1)]
finished = set([node_par[start]])
dfs(start,0,ans_height)
print(max(ans_height) + aoki[start] - 1)

Submission status: Time Limit Exceeded

Solution code:
import sys
sys.setrecursionlimit(10**6)

n,u,v = map(int, input().split())
adjacent_list = [[]for i in range(n+1)]
aoki = [0 for i in range(n+1)]
takahashi = [0 for i in range(n+1)]
for i in range(n-1):
    a,b = map(int ,input().split())
    adjacent_list[a].append(b)
    adjacent_list[b].append(a)

def dfs(node, count,li):
    li[node] = count
    finished.add(node)
    for i in adjacent_list[node]:
        if i not in finished:
            dfs(i, count + 1,li)
def dfs_par(node, count,li):
    global node_par
    li[node] = count
    finished.add(node)
    for i in adjacent_list[node]:
        if i not in finished:
            node_par[i] = node
            dfs_par(i, count + 1,li)
        
node_par = [0 for i in range(n+1)]

finished = set()
dfs(u,0,takahashi)

finished = set()
dfs_par(v,0,aoki)

#さかのぼれるとこまで行く
par = u
start = u

while takahashi[par] < aoki[par]:
    start = par
    par = node_par[start]

ans_height = [0 for i in range(n+1)]
finished = set([node_par[start]])
dfs(start,0,ans_height)
print(max(ans_height) + aoki[start] - 1)