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: Wrong Answer

Solution code:
from collections import deque
from math import ceil

def read():
    N, u, v = list(map(int, input().strip().split()))
    G = [list() for i in range(N+1)]
    for i in range(N-1):
        a, b = list(map(int, input().strip().split()))
        G[a].append(b)
        G[b].append(a)
    return N, u, v, G

def bfs(G, N, start, INF):
    D = [INF for i in range(N+1)]
    D[start] = 0
    q = deque()
    q.appendleft(start)
    while(len(q) > 0):
        s = q.pop()
        for i in range(len(G[s])):
            t = G[s][i]
            if D[t] == INF:
                D[t] = D[s] + 1
                q.appendleft(t)
    return D

def bfs_fill(G, N, start, du, INF, terminal):
    visited = [-1 for i in range(N+1)]
    visited[start] = 1
    D = [x for x in du] 
    D[start] = INF
    q = deque()
    q.appendleft(start)
    while(len(q) > 0):
        s = q.pop()
        for i in range(len(G[s])):
            t = G[s][i]
            if visited[t] == -1:
                visited[t] = 1
                if D[t] == terminal:
                    return D
                D[t] = INF
                q.appendleft(t)
    return D


def solve(N, u, v, G, INF=-1000000):
    du = bfs(G, N, u, INF)
    max_depth = (du[v] - du[u] - 1) // 2
    du2 = bfs_fill(G, N, v, du, INF, max_depth)
    return max(du2) + (du[v] - du[u] + 1) % 2


if __name__ == '__main__':
    inputs = read()
    print("%d" % solve(*inputs))

Submission status: Wrong Answer

Solution code:
import sys
sys.setrecursionlimit(10**5)
n, u, v = map(int, input().split())
u, v = u - 1, v - 1
nodes = [[] for i in range(n)]
for i in range(n - 1):
    a, b = map(int, input().split())
    a, b = a - 1, b - 1
    nodes[a].append(b)
    nodes[b].append(a)


def search(parent, node, depth):
    chokudai_depth = 0
    max_depth = depth
    if node == u:
        chokudai_depth = depth
    if len(nodes[node]) == 1 and parent != -1:
        return max_depth, chokudai_depth
    for child in nodes[node]:
        if child != parent:
            _max_depth, _chokudai_depth = search(node, child, depth + 1)
            max_depth = max(max_depth, _max_depth)
            chokudai_depth = max(chokudai_depth, _chokudai_depth)
    return max_depth, chokudai_depth


max_depth, chokudai_depth = search(-1, v, 0)
ans = max_depth - chokudai_depth
if chokudai_depth == 0:
    print(0)
else:
    ans += chokudai_depth - 1
    print(ans)

Submission status: Wrong Answer

Solution code:
n,x,y=map(int,input().split())
s=[[]for i in range(n+1)]
for i in range(n-1):
    a,b=map(int,input().split())
    s[a].append(b)
    s[b].append(a)
p=[float("INF")for i in range(n+1)]
q=[float("INF")for i in range(n+1)]
p[x]=0
q[y]=0
c=set([x])
while c:
    d=set()
    for i in c:
        for j in s[i]:
            if p[j]>p[i]+1:
                p[j]=p[i]+1
                d.add(j)
    c=d
c=set([y])
while c:
    d=set()
    for i in c:
        for j in s[i]:
            if q[j]>q[i]+1:
                q[j]=q[i]+1
                d.add(j)
    c=d
a,b,c=0,1,n
for i in range(1,n+1):
    if p[i]<q[i]:
        a=max(a,q[i]-(q[i]-p[i])%2)
    elif p[i]==q[i]:
        b=0
        c=min(c,p[i])
if b:
    print(a)
else:
    print(max(a,c))

Submission status: Wrong Answer

Solution code:
import heapq;

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

vert = []

for i in range(n):
    vert.append([])

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

taka = u-1
aoki = v-1

if taka == aoki:
    print(0)
    exit()

q = [(0, aoki)]
aoki_dist = [-1] * n
aoki_dist[aoki] = 0

index = 0
while index < len(q):
    c0, i = q[index]
    c = c0 + 1
    for l in vert[i]:
        if aoki_dist[l] >= 0:
            continue
        aoki_dist[i] = c
        q.append((c, l))
    index += 1

q = [(0, taka)]
max_dist = aoki_dist[taka]

index = 0
while index < len(q):
    c0, i = q[index]
    c = c0 + 1
    for l in vert[i]:
        if aoki_dist[l] < 0:
            continue
        if c > aoki_dist[l]:
            aoki_dist[l] = -1
            continue
        if max_dist < aoki_dist[l]:
            max_dist = aoki_dist[l]
        aoki_dist[l] = -1
        if c == aoki_dist[l]:
            continue
        q.append((c, l))
    index += 1

print(max_dist - 1)

Submission status: Wrong Answer

Solution code:
import sys
import collections


def solve():
    readline = sys.stdin.buffer.readline
    mod = 10 ** 9 + 7
    n, u, v = list(map(int, readline().split()))
    tmd = collections.defaultdict(list)
    for i in range(n-1):
        tma, tmb = list(map(int, readline().split()))
        tmd[tma-1] += [tmb-1]
        tmd[tmb-1] += [tma-1]

    qlt = [[0, u-1]]
    qlt = collections.deque(qlt)
    fqt = collections.defaultdict(int)
    fqt[u-1]
    while True:
        if len(qlt) != 0:
            cost, tmp = qlt.popleft()
            for tmv in tmd[tmp]:
                if tmv not in fqt:
                    qlt.append([cost + 1, tmv])
                    fqt[tmv] = cost + 1
        else:
            break

    qla = [[0, v-1]]
    qla = collections.deque(qla)
    fqa = collections.defaultdict(int)
    fqa[v-1]
    while True:
        if len(qla) != 0:
            cost, tmp = qla.popleft()
            for tmv in tmd[tmp]:
                if tmv not in fqa:
                    qla.append([cost + 1, tmv])
                    fqa[tmv] = cost + 1
        else:
            break
    mt = 0
    for kt, vt in sorted(fqt.items(), key=lambda x: x[1], reverse=True):
        if vt < fqa[kt]:
            mt = max(mt, vt)
    print(mt)


if __name__ == '__main__':
    solve()

Submission status: Wrong Answer

Solution code:
import os
import sys

if os.getenv("LOCAL"):
    sys.stdin = open("_in.txt", "r")

sys.setrecursionlimit(10 ** 9)
INF = float("inf")
IINF = 10 ** 18
MOD = 10 ** 9 + 7
# MOD = 998244353

N, V, U = list(map(int, sys.stdin.buffer.readline().split()))
AB = [list(map(int, sys.stdin.buffer.readline().split())) for _ in range(N - 1)]

V -= 1
U -= 1
graph = [[] for _ in range(N)]
for a, b in AB:
    a -= 1
    b -= 1
    graph[a].append(b)
    graph[b].append(a)

# 深い方に逃げるべき
# 子どものうち一番深い場所の深さ
children_depths = [-1 for _ in range(N)]
parents = [None for _ in range(N)]


def dfs(v, parent):
    ret = 0
    for u in graph[v]:
        if u == parent:
            continue
        ret = max(ret, dfs(u, v) + 1)
    children_depths[v] = ret
    parents[v] = parent
    return ret


dfs(U, None)

Submission status: Wrong Answer

Solution code:
import heapq;

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

vert = []

for i in range(n):
    vert.append([])

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

taka = u-1
aoki = v-1

if taka == aoki:
    print(0)
    exit()

q = [(0, aoki)]
aoki_dist = [-1] * n
aoki_dist[aoki] = 0

index = 0
while index < len(q):
    c0, i = q[index]
    c = c0 + 1
    for l in vert[i]:
        if aoki_dist[l] >= 0:
            continue
        aoki_dist[i] = c
        q.append((c, l))
    index += 1

q = [(0, taka)]
max_dist = aoki_dist[taka]

index = 0
while index < len(q):
    c0, i = q[index]
    c = c0 + 1
    for l in vert[i]:
        if aoki_dist[l] < 0:
            continue
        if c > aoki_dist[l]:
            continue
        if max_dist < aoki_dist[l]:
            max_dist = aoki_dist[l]
        aoki_dist[l] = -1
        q.append((c, l))
    index += 1

print(max_dist - 1)

Submission status: Wrong Answer

Solution code:
def p_f():
    from sys import stdin
    input = stdin.readline
    N, u, v = map(int, input().split())
    edges = [list(map(int, input().split())) for i in range(N - 1)]
    if u == v:
        print(0)
        exit()

    def BFS(K, edges, N):
        roots = [[] for i in range(N)]
        for a, b in edges:
            roots[a - 1] += [(b - 1, 1)]
            roots[b - 1] += [(a - 1, 1)]
        dist = [-1] * N
        stack = []
        stack.append(K)
        dist[K] = 0
        while stack:
            label = stack.pop(-1)
            for i, c in roots[label]:
                if dist[i] == -1:
                    dist[i] = dist[label] + c
                    stack += [i]
        return dist

    dist_v = BFS(v - 1, edges, N)
    dist_u = BFS(u - 1, edges, N)
    # print(dist_v)
    # print(dist_u)
    if max(dist_v) > dist_u[dist_v.index(max(dist_v))]:
        print(max(dist_v) - 1)
        exit()
    if dist_v[u - 1] > max(dist_v) - dist_v[u - 1]:
        print(max(dist_v) - 1)
    else:
        print(dist_v[u - 1] - 1)


if __name__ == '__main__':
    p_f()

Submission status: Wrong Answer

Solution code:
from heapq import heappush,heappop,heapify
from collections import deque,defaultdict,Counter
import itertools
from itertools import permutations,combinations
import sys
import bisect
import string
import math
import time
import random
def I():
    return int(input())
def MI():
    return map(int,input().split())
def LI():
    return [int(i) for i in input().split()]
def LI_():
    return [int(i)-1 for i in input().split()]
def StoI():
    return [ord(i)-97 for i in input()]
def ItoS(nn):
    return chr(nn+97)
def GI(V,E,Directed=False,index=0):
    org_inp=[]
    g=[[] for i in range(n)]
    for i in range(E):
        inp=LI()
        org_inp.append(inp)
        if index==0:
            inp[0]-=1
            inp[1]-=1
        if len(inp)==2:
            a,b=inp
            g[a].append(b)
            if not Directed:
                g[b].append(a)
        elif len(inp)==3:
            a,b,c=inp
            aa=(inp[0],inp[2])
            bb=(inp[1],inp[2])
            g[a].append(bb)
            if not Directed:
                g[b].append(aa)
    return g,org_inp
def show(*inp,end='\n'):
    if show_flg:
        print(*inp,end=end)
YN=['Yes','No']
mo=10**9+7
inf=float('inf')
l_alp=string.ascii_lowercase
u_alp=string.ascii_uppercase
ts=time.time()
#sys.setrecursionlimit(10**5)
input=lambda: sys.stdin.readline().rstrip()

def ran_input():
    import random
    n=random.randint(4,16)
    rmin,rmax=1,10
    a=[random.randint(rmin,rmax) for _ in range(n)]
    return n,a

show_flg=False
show_flg=True
#for i in range(n):

ans=0

n,t,a=LI_()
n+=1
g,c=GI(n,n-1)

#for i in range(1,30):


#vにはdepthをセット & -1 で未訪問フラグ

v=[-1]*(n)

def bfs(x):  # x スタート
    p=deque()
    p.append(x)
    v[x]=0
    while p:
        c=p.popleft()
        for i in g[c]:
            if v[i]==-1:
                p.append(i)
                v[i]=v[c]+1
    return

w=[-1]*(n)

def t_bfs(x):  # x スタート
    ans=0
    p=deque()
    p.append(x)
    w[x]=0
    while p:
        c=p.popleft()
        for i in g[c]:
            if w[i]==-1:
                p.append(i)
                #w[i]=w[c]+1
                if w[c]+1==v[i]:
                    ans=max(ans,v[i])
                #if w[c]+1>=v[i]:
                if w[c]+1>v[i]:
                    w[i]=-inf
                else:
                    w[i]=w[c]+1
                    #ans=max(ans,v[i]-(1 if (v[i]-w[i])%2==0 else 0))
                if len(g[c])==1:
                    ans=max(ans,v[c])
                
                
    return ans


bfs(a)
ans=t_bfs(t)

#print(max(0,ans-1))
print(ans)

Submission status: Wrong Answer

Solution code:
# -*- coding: utf-8 -*-

import sys

def input(): return sys.stdin.readline().strip()
def list2d(a, b, c): return [[c] * b for i in range(a)]
def list3d(a, b, c, d): return [[[d] * c for j in range(b)] for i in range(a)]
def list4d(a, b, c, d, e): return [[[[e] * d for j in range(c)] for j in range(b)] for i in range(a)]
def ceil(x, y=1): return int(-(-x // y))
def INT(): return int(input())
def MAP(): return map(int, input().split())
def LIST(N=None): return list(MAP()) if N is None else [INT() for i in range(N)]
def Yes(): print('Yes')
def No(): print('No')
def YES(): print('YES')
def NO(): print('NO')
sys.setrecursionlimit(10 ** 9)
INF = 10 ** 18
MOD = 10 ** 9 + 7

N, x, y = MAP()
x -= 1; y -= 1
nodes = [[] for i in range(N)]
for i in range(N-1):
    a, b = MAP()
    a -= 1; b -= 1
    nodes[a].append(b)
    nodes[b].append(a)

memo  = [-1] * N
stack = [(y, 0, -1)]
while stack:
    u, cost, prev = stack.pop()
    if memo[u] != -1:
        continue
    memo[u] = cost
    for v in nodes[u]:
        if v == prev:
            continue
        stack.append((v, cost+1, u))
memo2  = [-1] * N
stack = [(x, 0, -1)]
while stack:
    u, cost, prev = stack.pop()
    if memo2[u] != -1:
        continue
    memo2[u] = cost
    if u == y:
        continue
    for v in nodes[u]:
        if v == prev:
            continue
        stack.append((v, cost+1, u))

for i in range(N):
    if memo[i] < memo2[i]:
        memo2[i] = -1
mx = mx2 = -1
for u, val in enumerate(memo2):
    val2 = memo[u]
    if val2 - val > mx:
        mx = val2 - val
        mx2 = val2
    elif val2 - val == mx:
        if val2 > mx2:
            mx2 = val2
print(mx2 - 1)

Submission status: Wrong Answer

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

n, u, v = map(int, input().split())
ab = [list(map(int, input().split())) for _ in range(n-1)]

graph = [[] for _ in range(n)]
for a, b in ab:
    graph[a-1].append(b-1)
    graph[b-1].append(a-1)


def dfs(graph, start):
    visited = [0]*n
    stack = deque([start])
    distance = [-1]*n
    dis = 0
    while stack:
        node = stack.pop()
        visited[node] = 1
        if len(graph[node]) == 1:
            if node == start:
                distance[node] = 0
            else:
                distance[node] = dis
                dis -= 1
        for child in graph[node]:
            if visited[child] == 1:
                continue
            stack.append(child)
        dis += 1
    return distance

distance1 = np.array(dfs(graph, u-1))
distance2 = np.array(dfs(graph, v-1))

distance = distance2[distance1<distance2]

print(min(distance)-1)

Submission status: Wrong Answer

Solution code:
import heapq;

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

vert = []

for i in range(n):
    vert.append([])

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

taka = u-1
aoki = v-1

if taka == aoki:
    print(0)
    exit()

q = [(0, aoki)]
aoki_dist = [-1] * n
aoki_dist[aoki] = 0

index = 0
while index < len(q):
    c0, i = q[index]
    c = c0 + 1
    for l in vert[i]:
        if aoki_dist[l] >= 0:
            continue
        aoki_dist[i] = c
        q.append((c, l))
    index += 1

q = [(0, taka)]
max_dist = aoki_dist[taka]

index = 0
while index < len(q):
    c0, i = q[index]
    c = c0 + 1
    for l in vert[i]:
        if aoki_dist[l] < 0:
            continue
        if c >= aoki_dist[l]:
            continue
        if max_dist < aoki_dist[l]:
            max_dist = aoki_dist[l]
        aoki_dist[l] = -1
        q.append((c, l))
    index += 1

print(max_dist - 1)

Submission status: Wrong Answer

Solution code:
from heapq import heappush,heappop,heapify
from collections import deque,defaultdict,Counter
import itertools
from itertools import permutations,combinations
import sys
import bisect
import string
import math
import time
import random
def I():
    return int(input())
def MI():
    return map(int,input().split())
def LI():
    return [int(i) for i in input().split()]
def LI_():
    return [int(i)-1 for i in input().split()]
def StoI():
    return [ord(i)-97 for i in input()]
def ItoS(nn):
    return chr(nn+97)
def GI(V,E,Directed=False,index=0):
    org_inp=[]
    g=[[] for i in range(n)]
    for i in range(E):
        inp=LI()
        org_inp.append(inp)
        if index==0:
            inp[0]-=1
            inp[1]-=1
        if len(inp)==2:
            a,b=inp
            g[a].append(b)
            if not Directed:
                g[b].append(a)
        elif len(inp)==3:
            a,b,c=inp
            aa=(inp[0],inp[2])
            bb=(inp[1],inp[2])
            g[a].append(bb)
            if not Directed:
                g[b].append(aa)
    return g,org_inp
def show(*inp,end='\n'):
    if show_flg:
        print(*inp,end=end)
YN=['Yes','No']
mo=10**9+7
inf=float('inf')
l_alp=string.ascii_lowercase
u_alp=string.ascii_uppercase
ts=time.time()
#sys.setrecursionlimit(10**5)
input=lambda: sys.stdin.readline().rstrip()

def ran_input():
    import random
    n=random.randint(4,16)
    rmin,rmax=1,10
    a=[random.randint(rmin,rmax) for _ in range(n)]
    return n,a

show_flg=False
show_flg=True
#for i in range(n):

ans=0

n,t,a=LI_()
n+=1
g,c=GI(n,n-1)

#for i in range(1,30):


#vにはdepthをセット & -1 で未訪問フラグ

v=[-1]*(n)

def bfs(x):  # x スタート
    p=deque()
    p.append(x)
    v[x]=0
    while p:
        c=p.popleft()
        for i in g[c]:
            if v[i]==-1:
                p.append(i)
                v[i]=v[c]+1
    return

w=[-1]*(n)

def t_bfs(x):  # x スタート
    ans=0
    p=deque()
    p.append(x)
    w[x]=0
    while p:
        c=p.popleft()
        for i in g[c]:
            if w[i]==-1:
                p.append(i)
                #w[i]=w[c]+1
                if w[c]+1==v[i]:
                    0#ans=max(ans,v[i])
                #if w[c]+1>=v[i]:
                if w[c]+1>v[i]:
                    
                    w[i]=-inf
                else:
                    w[i]=w[c]+1
                    #ans=max(ans,v[i]-(1 if (v[i]-w[i])%2==0 else 0))
                if len(g[c])==1:
                    ans=max(ans,v[c])
                
                
    return ans


bfs(a)
ans=t_bfs(t)

#print(max(0,ans-1))
print(ans)

Submission status: Wrong Answer

Solution code:
#メモ，葉もしくはその一つ手前でぶつかるはず？
import heapq
class Dijkstra():
    """
    ・有向 / 無向は問わない(無向の場合は，逆向きの辺もたす)
    ・負のコストがない場合のみ
    ・計算量はO(E log|V|)　
    ・heapを使うことで頂点を走査する必要がなくなる（代わりに，距離更新したものは確定でなくともqueに入れておく）
    """
    
    #最短のpathをたす
    
    
    class Edge():
        #重み付き有向辺
        
        def __init__(self, _to, _cost):
            self.to =_to
            self.cost = _cost
    
    def __init__(self, V):
        #引数Vは頂点数
        self.G = [[] for _ in range(V)] #隣接リストG[u][i]が頂点uのi番目の辺
        self. _E = 0 #辺の数
        self._V = V #頂点数
    
    #proparty - 辺の数
    def E(self):
        return self._E
    
    #proparty - 頂点数
    def V(self):
        return self._V
    
    def add(self, _from, _to, _cost):
        #2頂点と辺のコストを追加
        self.G[_from].append(self.Edge(_to,_cost))
        self._E +=1
        
    def add2(self, _from, _to, _cost):
        #2頂点と辺のコスト（無向）を追加
        self.G[_from].append(self.Edge(_to, _cost))
        self.G[_to].append(self.Edge(_from, _cost))
        self._E +=1
        
    def shortest_path(self,s):
        #始点sから頂点iまでの最短経路長のリストを返す
        
        que = [] #priority queue
        d = [float("inf")] * self.V()
        prev = [None]*self.V() #prev[j]は，sからjへ最短経路で行くときのjの一つ前の場所
        d[s] = 0
        heapq.heappush(que,(0,s)) #始点の距離と頂点番号をヒープに追加
        
        while len(que)!=0:
            #キューに格納されてある中で一番コストが小さい頂点を取り出す
            cost,v = heapq.heappop(que)
            
            #キューに格納された最短経路長候補がdの距離よりも大きい場合に処理をスキップ
            if d[v] < cost:
                continue
                
            #頂点vに隣接する各頂点iに対して，vを経由した場合の距離を計算して，これがd[i]よりも小さい場合に更新
            for i in range(len(self.G[v])):
                e = self.G[v][i] #vのi個目の隣接辺
                if d[e.to] > d[v] + e.cost:
                    d[e.to] = d[v] + e.cost #更新
                    prev[e.to] = v
                    heapq.heappush(que,(d[e.to],e.to)) #queに新たな最短経路長候補を追加
                    
        return d

    

N, u, v = map(int, input().split())
list=[[] for _ in range(N)]
djk = Dijkstra(N)

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



d=djk.shortest_path(v-1)
path_to_leaf=[]

for i in range(N):
    if len(list[i])==1:
        path_to_leaf.append(d[i])
        #print(i)

ans = max(path_to_leaf)-1
print(ans)

Submission status: Wrong Answer

Solution code:
import copy
import sys
input = sys.stdin.readline
N,U,V = map(int, input().split())
d = [set() for _ in range(N+1)]
dps = [0 for _ in range(N+1)]
dpss = [0 for _ in range(N+1)]
oks = set()
r = {}

def it(v):
    stack = [v]
    vs = set()
    path = []
    while True:
        if not len(stack):
            break
        v = stack.pop()
        path.append(v)
        if v > 0:
            vs.add(v)
            for u in d[v]:
                if u in vs:
                    continue
                if u == V:
                    r = path[:]
                dps[u] = dps[v] + 1
                oks.add(u)
                stack.append(-v)
                stack.append(u)
        else:
            path.pop()
    return r

def it2(v, path):
    stack = [v]
    vs = set()
    while True:
        if not len(stack):
            break
        v = stack.pop()
        vs.add(v)
        for u in d[v]:
            if u in vs:
                continue
            if u not in oks:
                continue
            if dps[v] >= dpss[v] and u not in path:
                continue
            dpss[u] = dpss[v] + 1
            stack.append(u)

for _ in range(N-1):
    a, b = [int(x) for x in input().split()]
    d[a].add(b)
    d[b].add(a)

oks.add(U)
path = set(it(U))
it2(V, path)
print(max(dpss)-1)

Submission status: Wrong Answer

Solution code:
import sys
sys.setrecursionlimit(10**5+1)

def cur(p):
    for i in x[p]:
        if rank[i]==-1:
            rank[i]=rank[p]+1
            par[i]=p
            cur(i)

def cur2(p):
    if spar[p]==-1:
        spar[p]=cur2(par[p])
    return spar[p]




n,u,v=map(int,input().split())
u,v=u-1,v-1
x=[[] for i in range(n)]

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

rank=[-1 for i in range(n)]
rank[u]=0
par=[-1 for i in range(n)]

cur(u)

spar=[-1 for i in range(n)]
i=v
while i!=u:
    spar[i]=i
    i=par[i]
spar[u]=u


for p in range(n):
    cur2(p)

ans=rank[v]-1
for i in range(n):
    z=rank[v]-rank[spar[i]]*2
    if z>0:
        ans=max(0,rank[i]+z-1)
print(ans)

Submission status: Wrong Answer

Solution code:
from heapq import heappush,heappop,heapify
from collections import deque,defaultdict,Counter
import itertools
from itertools import permutations,combinations
import sys
import bisect
import string
import math
import time
import random
def I():
    return int(input())
def MI():
    return map(int,input().split())
def LI():
    return [int(i) for i in input().split()]
def LI_():
    return [int(i)-1 for i in input().split()]
def StoI():
    return [ord(i)-97 for i in input()]
def ItoS(nn):
    return chr(nn+97)
def GI(V,E,Directed=False,index=0):
    org_inp=[]
    g=[[] for i in range(n)]
    for i in range(E):
        inp=LI()
        org_inp.append(inp)
        if index==0:
            inp[0]-=1
            inp[1]-=1
        if len(inp)==2:
            a,b=inp
            g[a].append(b)
            if not Directed:
                g[b].append(a)
        elif len(inp)==3:
            a,b,c=inp
            aa=(inp[0],inp[2])
            bb=(inp[1],inp[2])
            g[a].append(bb)
            if not Directed:
                g[b].append(aa)
    return g,org_inp
def show(*inp,end='\n'):
    if show_flg:
        print(*inp,end=end)
YN=['Yes','No']
mo=10**9+7
inf=float('inf')
l_alp=string.ascii_lowercase
u_alp=string.ascii_uppercase
ts=time.time()
#sys.setrecursionlimit(10**5)
input=lambda: sys.stdin.readline().rstrip()

def ran_input():
    import random
    n=random.randint(4,16)
    rmin,rmax=1,10
    a=[random.randint(rmin,rmax) for _ in range(n)]
    return n,a

show_flg=False
show_flg=True
#for i in range(n):

ans=0

n,t,a=LI_()
n+=1
g,c=GI(n,n-1)

#for i in range(1,30):


#vにはdepthをセット & -1 で未訪問フラグ

v=[-1]*(n)

def bfs(x):  # x スタート
    p=deque()
    p.append(x)
    v[x]=0
    while p:
        c=p.popleft()
        for i in g[c]:
            if v[i]==-1:
                p.append(i)
                v[i]=v[c]+1
    return

w=[-1]*(n)

def t_bfs(x):  # x スタート
    ans=0
    p=deque()
    p.append(x)
    w[x]=0
    while p:
        c=p.popleft()
        for i in g[c]:
            if w[i]==-1:
                p.append(i)
                #w[i]=w[c]+1
                if w[c]+1==v[i]:
                    0#ans=max(ans,v[i])
                if w[c]+1>=v[i]:
                #if w[c]+1>v[i]:
                    
                    w[i]=-inf
                else:
                    w[i]=w[c]+1
                    #ans=max(ans,v[i]-(1 if (v[i]-w[i])%2==0 else 0))
                if len(g[c])==1:
                    ans=max(ans,v[c])
                
                
    return ans


bfs(a)
ans=t_bfs(t)

#print(max(0,ans-1))
print(ans)

Submission status: Wrong Answer

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

import heapq
def dijkstra_heap(s):
    #始点sから各頂点への最短距離
    d = [float("inf")] * n
    used = [True] * n #True:未確定
    d[s] = 0
    used[s] = False
    edgelist = []
    for e in edge[s]:
        heapq.heappush(edgelist,e)
    while len(edgelist):
        minedge = heapq.heappop(edgelist)
        #まだ使われてない頂点の中から最小の距離のものを探す
        if not used[minedge[1]]:
            continue
        v = minedge[1]
        d[v] = minedge[0]
        used[v] = False
        for e in edge[v]:
            if used[e[1]]:
                heapq.heappush(edgelist,[e[0]+d[v],e[1]])
    return d

#n,w = map(int,input().split()) #n:頂点数　w:辺の数
edge = [[] for i in range(n)]
#edge[i] : iから出る道の[重み,行先]の配列
for i in range(n-1):
    z=1
    x,y = map(int,input().split())
    x-=1;y-=1
    edge[x].append([z,y]) #有向辺
    edge[y].append([z,x]) #有向辺
A=dijkstra_heap(u)
B=dijkstra_heap(v)
l=[]
for i in range(n):
    l.append([A[i],B[i]])
l.sort()
l=l[::-1]
ans=float('inf')
for i in range(n-1):
    if l[i][0]<l[i][1]:
        print(l[i][0])
        break
else:
    print(1)

Submission status: Wrong Answer

Solution code:
import heapq;

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

vert = []

for i in range(n):
    vert.append([])

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

taka = u-1
aoki = v-1

q = [(0, aoki)]
aoki_dist = [-1] * n
aoki_dist[aoki] = 0

index = 0
while index < len(q):
    c0, i = q[index]
    c = c0 + 1
    for l in vert[i]:
        if aoki_dist[l] >= 0:
            continue
        aoki_dist[i] = c
        q.append((c, l))
    index += 1

q = [(0, taka)]
max_dist = aoki_dist[taka]

index = 0
while index < len(q):
    c0, i = q[index]
    c = c0 + 1
    for l in vert[i]:
        if aoki_dist[l] < 0:
            continue
        if c >= aoki_dist[l]:
            continue
        if max_dist < aoki_dist[l]:
            max_dist = aoki_dist[l]
        aoki_dist[l] = -1
        q.append((c, l))
    index += 1

print(max_dist - 1)

Submission status: Wrong Answer

Solution code:
from heapq import heappush,heappop,heapify
from collections import deque,defaultdict,Counter
import itertools
from itertools import permutations,combinations
import sys
import bisect
import string
import math
import time
import random
def I():
    return int(input())
def MI():
    return map(int,input().split())
def LI():
    return [int(i) for i in input().split()]
def LI_():
    return [int(i)-1 for i in input().split()]
def StoI():
    return [ord(i)-97 for i in input()]
def ItoS(nn):
    return chr(nn+97)
def GI(V,E,Directed=False,index=0):
    org_inp=[]
    g=[[] for i in range(n)]
    for i in range(E):
        inp=LI()
        org_inp.append(inp)
        if index==0:
            inp[0]-=1
            inp[1]-=1
        if len(inp)==2:
            a,b=inp
            g[a].append(b)
            if not Directed:
                g[b].append(a)
        elif len(inp)==3:
            a,b,c=inp
            aa=(inp[0],inp[2])
            bb=(inp[1],inp[2])
            g[a].append(bb)
            if not Directed:
                g[b].append(aa)
    return g,org_inp
def show(*inp,end='\n'):
    if show_flg:
        print(*inp,end=end)
YN=['Yes','No']
mo=10**9+7
inf=float('inf')
l_alp=string.ascii_lowercase
u_alp=string.ascii_uppercase
ts=time.time()
#sys.setrecursionlimit(10**5)
input=lambda: sys.stdin.readline().rstrip()

def ran_input():
    import random
    n=random.randint(4,16)
    rmin,rmax=1,10
    a=[random.randint(rmin,rmax) for _ in range(n)]
    return n,a

show_flg=False
show_flg=True
#for i in range(n):

ans=0

n,t,a=LI_()
n+=1
g,c=GI(n,n-1)

#for i in range(1,30):


#vにはdepthをセット & -1 で未訪問フラグ

v=[-1]*(n)

def bfs(x):  # x スタート
    p=deque()
    p.append(x)
    v[x]=0
    while p:
        c=p.popleft()
        for i in g[c]:
            if v[i]==-1:
                p.append(i)
                v[i]=v[c]+1
    return

w=[-1]*(n)

def t_bfs(x):  # x スタート
    ans=0
    p=deque()
    p.append(x)
    w[x]=0
    while p:
        c=p.popleft()
        for i in g[c]:
            if w[i]==-1:
                p.append(i)
                #w[i]=w[c]+1
                if w[c]+1==v[i]:
                    0#ans=max(ans,v[i])
                if w[c]+1>=v[i]:
                #if w[c]+1>v[i]:
                    
                    w[i]=-inf
                else:
                    w[i]=w[c]+1
                    #ans=max(ans,v[i]-(1 if (v[i]-w[i])%2==0 else 0))
                if (w[c]+1-v[i])==1:
                    ans=max(ans,v[i])
                
                
    return ans


bfs(a)
ans=t_bfs(t)

#print(max(0,ans-1))
print(ans)

Submission status: Wrong Answer

Solution code:
import sys
from collections import deque

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

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

memo = [[0, 0] for i in range(n)]

def dfs(cur, pre, p):
    stack = deque([[cur, pre]])
    while stack:
        cur, pre = stack.pop()
        if pre != -1:
            memo[cur][p] = memo[pre][p] + 1
        for e in E[cur]:
            if e != pre:
                stack.append([e, cur])

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

# print(memo)
ans = 0
for a, b in memo:
    if a >= b:
        ans = max(ans, b - 1)
print(ans)