Harryxun/sft_time huggingface dataset:
### BUGGY CODE ###

#coding:utf-8
n,m = map(int,input().split())
List = list(map(int,input().split()))


forest = [i for i in range(n+1)]
rank = [0 for i in range(n+1)]

def unite(x,y):
    while forest[x] != x:
        x = forest[x]
    a = rank[x]
    
    while forest[y] != y:
        y = forest[y]
    b = rank[y]
    
    if a <= b:
        if a == b:
            rank[x] += 1
        forest[y] = x
    else:
        forest[x] = y


def Find(x,y):
    Q = []
    P = []
    while forest[x] != x:
        x = forest[x]
        Q.append(x)
            
    while forest[y] != y:
        y = forest[y]
        P.append(y)
    for xi in Q:
        forest[xi] = x
        rank[xi] = 1
    for yi in P:
        forest[yi] = y
        rank[yi] = 1
    if x == y:
        return 1
    else:
        return 0
    
cnt = 0
for i in range(m):
    x,y = map(int,input().split())
    unite(x,y)

for i in range(1,n+1):
    cnt += Find(i,List[i-1])
print(cnt)
    


### FIXED CODE ###

#coding:utf-8

n,m = map(int,input().split())
List = list(map(int,input().split()))

class UnionFind3:
    def __init__(self, size):
        # 負の値はルート (集合の代表) で集合の個数
        # 正の値は次の要素を表す
        self.table = [-1 for i in range(size)]

    # 集合の代表を求める
    def find(self, x):
        if self.table[x] < 0:
            return x
        else:
            # 経路の圧縮
            self.table[x] = self.find(self.table[x])
            return self.table[x]

    # 併合
    def union(self, x, y):
        s1 = self.find(x)
        s2 = self.find(y)
        if s1 != s2:
            if self.table[s1] <= self.table[s2]:
                # 小さいほうが個数が多い
                self.table[s1] += self.table[s2]
                self.table[s2] = s1
            else:
                self.table[s2] += self.table[s1]
                self.table[s1] = s2
            return 1
        return 0


cnt = 0
tree = UnionFind3(n)
for i in range(m):
    x,y = map(int,input().split())
    tree.union(x-1,y-1)

for i in range(n):
    a = tree.find(i)
    b = tree.find(List[i]-1)
    if a == b:
        cnt += 1

print(cnt)
### BUGGY CODE ###

import numpy as np
from scipy.sparse.csgraph import dijkstra
from scipy.sparse import csr_matrix
# from scipy.special import comb,perm #permはnPk

N,M = map(int,input().split())
length = N

i = [] #頂点(始点)
j = [] #頂点(終点)
d = [] #頂点間の距離
for _ in range(M):
    A,B = map(int,input().split())
    i.append(A-1)
    j.append(B-1)
    d.append(1)

graph = csr_matrix((d, (i, j)), shape=(N, N)) # 頂点i,jはゼロスタートである必要ある

#返り値は各頂点間の距離の値を含んだ隣接行列(float64型のnp.array)
dist,pred = dijkstra(graph, directed=False,indices=0,return_predecessors=True,unweighted=True)

pred = pred + 1
print("Yes")
print(*pred[1:],sep="\n")

### FIXED CODE ###

# from math import factorial,sqrt,ceil #,gcd
# from itertools import permutations,combinations,combinations_with_replacement
# from collections import deque,Counter
# import re
# from bisect import bisect_left
# from heapq import heappush,heappop
# from numba import njit,jit
# from functools import lru_cache # 簡単メモ化 @lru_cache(maxsize=1000)
# from fractions import gcd

# from decimal import Decimal, getcontext
# # getcontext().prec = 1000
# # eps = Decimal(10) ** (-100)

# import numpy as np
from networkx import Graph
from networkx.algorithms.traversal.breadth_first_search import bfs_predecessors
G = Graph()
# from scipy.sparse.csgraph import shortest_path, dijkstra, floyd_warshall, bellman_ford, johnson
# from scipy.sparse import csr_matrix
# from scipy.special import comb,perm #permはnPk

# slist = "abcdefghijklmnopqrstuvwxyz"
N,M = map(int,input().split())
rows = [list(map(int,input().split())) for _ in range(M)]

G.add_edges_from(rows)

# shortestPath = shortest_path(G,target=1)
preds = bfs_predecessors(G,source=1)
# shortestPath = single_target_shortest_path(G,target=1)
# shortestPathLength,shortestPath = single_source_dijkstra(G,source=1)

preds = dict(preds)
if len(preds)+1 != N:
    print("No")
    exit()

print("Yes")
for i in range(2,N+1):
    print(preds[i])
### BUGGY CODE ###

N, M = map(int, input().split())
abl = []
for i in range(M):
    abl.append(list(map(int,input().split())))

counter = 0
island = 0
ans = 'IMPOSSIBLE'
for i in abl:
    if i[0] == 1:
        island = i[1]
        counter += 1
        for j in abl:
            if j[0] == island and j[1] == N:
                ans = 'POSSIBLE'
                print(ans)
                exit()

print(ans)


### FIXED CODE ###

N, M = map(int, input().split())

abl1 = set()
abl2 = set()
for _ in range(M):
    ab = list(map(int,input().split()))
    if ab[0] == 1:
        abl1.add(ab[1])
    elif ab[1] == N:
        abl2.add(ab[0])


for i in abl1:
   if i in abl2:
       print("POSSIBLE")
       exit()
print("IMPOSSIBLE")
### BUGGY CODE ###

N = int(input())
S = list(map(int, input().split()))
S.sort(reverse=True)
Closed = [False] * (1<<N)
Closed[0] = True
for _ in range(N):
    cnt = 0
    cnt_ = 0
    s_old = -1
    for i, s in enumerate(S):
        if s_old!=s:
            cnt += cnt_
            cnt_ = 0
        c = Closed[i]
        if c:
            cnt_ += 1
        elif cnt > 0:
            Closed[i] = True
            cnt -= 1
        s_old = s
if False in Closed:
    print("No")
else:
    print("Yes")


### FIXED CODE ###

N = int(input())
S = list(map(int, input().split()))
S.sort(reverse=True)
Closed = [False] * (1<<N)
Closed[0] = True
for _ in range(N):
    cnt = 0
    cnt_ = 0
    s_old = -1
    for i, s in enumerate(S):
        if s_old!=s:
            cnt += cnt_
            cnt_ = 0
        c = Closed[i]
        if c:
            cnt_ += 1
        elif cnt > 0:
            Closed[i] = True
            cnt -= 1
        s_old = s
if False in Closed:
    print("No")
else:
    print("Yes")
### BUGGY CODE ###

def main():
    N, K = list(map(int, input().split(' ')))
    A = list(map(int, input().split(' ')))
    if K >= N:
        print(' '.join([str(N) for _ in range(N)]))
        return
    for _ in range(K):
        imos = [0 for _ in range(N)]
        for i, a in enumerate(A):
            left = max(0, i - a)
            imos[left] += 1
            right = i + 1 + a
            if right <= N - 1:
                imos[right] -= 1
        for i in range(1, N):
            imos[i] += imos[i - 1]
        A = imos
    print(' '.join(map(str, A)))


if __name__ == '__main__':
    main()

### FIXED CODE ###

def main():
    N, K = list(map(int, input().split(' ')))
    A = list(map(int, input().split(' ')))
    if K >= 42:
        print(' '.join([str(N) for _ in range(N)]))
        return
    for _ in range(K):
        cumsum = [0 for _ in range(N)]
        for i, a in enumerate(A):
            left = max(0, i - a)
            cumsum[left] += 1
            right = i + 1 + a
            if right <= N - 1:
                cumsum[right] -= 1
        for i in range(1, N):
            cumsum[i] += cumsum[i - 1]
        A = cumsum
    print(' '.join(map(str, A)))
 
 
if __name__ == '__main__':
    main()
### BUGGY CODE ###

import sys
input=sys.stdin.buffer.readline
n=int(input())
l=list(map(int,input().split()))
f=1
from fractions import gcd

for i in l:
    f=f*i//gcd(f,i)
mod=10**9+7
ans=0
for i in l:
  ans+=f//i
print(ans%mod)


### FIXED CODE ###

def s():
  from sys import stdin
  read=stdin.buffer.readline
  n=int(read())
  l=list(map(int,read().split()))
  f=l[0]
  mod=10**9+7
  def gcd(s,d):
    s,d=max(s,d),min(s,d)
    while  d:
      s,d=d,s%d
    return s
  for i in l:
    f=i*f//gcd(i,f)
  ans=0
  for iu in l:
    b,u,v=mod,1,0
    while b:
      t=iu//b;iu,b=b,iu%b;u-=t*v;u,v=v,u
    ans+=(f*u%mod)%mod
    ans%=mod
  print(ans)
  
if __name__=="__main__":s()
### BUGGY CODE ###

N=int(input())
V1,V2={},{}
ans = N-1
for n,i in enumerate(list(map(int,input().split(' ')))):
    if n%2==0:
        V1.setdefault(i,0)
        V1[i]+=1
    else:
        V2.setdefault(i,0)
        V2[i]+=1
V1=sorted(V1.items(),key=lambda x:x[1])
V2=sorted(V2.items(),key=lambda x:x[1])
for i in V1:
    for j in V2:
        if i[0]!=j[0]:
            ans = min(ans,N-i[1]-j[1])
        else:
            ans = min(ans,N-max(i[1],j[1]))
print(ans)

### FIXED CODE ###

N=int(input())
V1,V2={},{}
ans = N-1
for n,i in enumerate(list(map(int,input().split(' ')))):
    if n%2==0:
        V1.setdefault(i,0)
        V1[i]+=1
    else:
        V2.setdefault(i,0)
        V2[i]+=1
V1=sorted(V1.items(),key=lambda x:x[1],reverse=True)
V2=sorted(V2.items(),key=lambda x:x[1],reverse=True)
cut = max(V1[0][1],V2[0][1])
for i in V1[:2]:
    for j in V2[:2]:
        if i[0]!=j[0]:
            ans = min(ans,N-i[1]-j[1])
        else:
            ans = min(ans,N-max(i[1],j[1]))
print(ans)
### BUGGY CODE ###

n,k = map(int,input().split())
a = list(map(int,input().split()))
a.sort(reverse=True)
hi = -1
lo = n
while lo-hi>1:
  mid = (lo+hi)//2
  if a[mid] >= k:
    hi = mid
  else:
    lo = mid
ng = hi
ok = n
while ok-ng > 1:
  mid = (ok+ng)//2
  dp = [False]*(k+1)
  dp[0] = True
  f = 1
  for j in range(n):
    if j == mid:
      f = 0
      continue
    w = a[j]
    new = dp.copy()
    for i in range(k-w+1):
      new[i+w] |= dp[i]
    dp = new
  if any(dp[k-a[mid]:k]):
    ng = mid
  else:
    ok = mid
print(n-ok)

### FIXED CODE ###

n, k = map(int,input().split())
a = [k+1 if x > k else x for x in map(int,input().split())]
a.sort()
lef = [1]*n
rig = [1]*n
mask = (1 << (k+1)) - 1
for i in range(n-1):
  lef[i+1] = lef[i] | (lef[i] << a[i]) & mask
  rig[-i-2] = rig[-i-1] | (rig[-i-1] << a[-i-1]) & mask
ok = -1
ng = n
while ng - ok > 1:
  mid = (ng + ok) // 2
  if a[mid] >= k:
      ng = mid
      continue
  lc = lef[mid]
  rc = rig[mid]
  cov = ((1 << k) - 1) ^ ((1 << (k - a[mid])) - 1)
  for i in range(k):
    if lc & 1 and rc & cov:
      ng = mid
      break
    lc >>= 1
    cov >>= 1
  else:
    ok = mid
print(ok + 1)
### BUGGY CODE ###

import sys

stdin = sys.stdin

ni = lambda: int(ns())
na = lambda: list(map(int, stdin.readline().split()))
ns = lambda: stdin.readline().rstrip()  # ignore trailing spaces

n, q = na()
s = input()
for i in range(q):
    l, r = na()
    flg = s[l-1:r]
    print(flg.count("AC"))

### FIXED CODE ###

import math,string,itertools,fractions,heapq,collections,re,array,bisect,sys,random,time

sys.setrecursionlimit(10**7)
inf = 10**20
mod = 10**9 + 7

stdin = sys.stdin

ni = lambda: int(ns())
na = lambda: list(map(int, stdin.readline().split()))
ns = lambda: stdin.readline().rstrip()  # ignore trailing spaces

n, q = na()
s = input()
ct = [0] * n
for i in range(n-1):
    if s[i:i+2] == 'AC':
        ct[i+1] = 1
for i in range(n-1):
    ct[i+1] += ct[i]
for i in range(q):
    l, r = na()
    l -= 1
    r -= 1
    print(ct[r] - ct[l])
### BUGGY CODE ###

def main():
  #1:初期化
  N, K = map(int,input().split())
  h = [int(i) for i in input().split()]
  #print(h,H)
  inf = float("inf")
  dp = [inf]*(N)

  #2:初期値
  dp[0] = 0

  #3:dp実行部(配るDP)
  for i in range(N):
      for k in range(1,min(N-i-1,K)+1):
          dp[i+k] = min(dp[i+k], dp[i] + abs(h[i] - h[i+k]))
          #print(dp,i,k)

  #4:出力
  print(dp[N-1])

if __name__ == '__main__':
    main()


### FIXED CODE ###

# -*- coding: utf-8 -*- 
def cost(h,N,K):
    dp=[0]*N
    dp[1]=abs(h[0]-h[1])
    for i in range(2,N):
        tmp=[abs(h[i]-h[j])+dp[j] for j in range(max(0,i-K),i)]
        dp[i]=min(tmp)
    return dp[-1]

N,K=map(int,input().split())
h=[int(num) for num in input().split()]

print(cost(h,N,K))
### BUGGY CODE ###

n=int(input())
a=list(map(int,input().split()))
res=1

z=10**18
for i in a:
    res*=i
    if(i>z):
        break
if(res>z):
    print(-1)
else:
    print(res)

### FIXED CODE ###

n=int(input())
a=list(map(int,input().split()))
a.sort()
res=1
z=10**18
for i in a:
    if(i==0):
        res=0
        break
i=n-1
while(i>=0):
    if(a[i]==0):
        res=0
        break
    if(res>z/a[i]):
        res=z+1
        break
    res*=a[i]
    if(a[i]>z):
        break
    i-=1
if(res>z):
    res=-1
print(res)
### BUGGY CODE ###

# coding: utf-8
# Your code here!

line = input()
data = line.split(" ")
shoplist = [] #店のデータリスト
for i in range(int(data[0])):
    shop = input()
    shopdata = shop.split(" ")
    shop_int = []
    for j in range(len(shopdata)):
        shop_int.append(int(shopdata[j]))
    shoplist.append(shop_int)
shoplist = sorted(shoplist)
payment = 0 #支払い金額
wantdrink = int(data[1]) #ほしい飲み物の数
while wantdrink > 0 :
    restdrink = shoplist[0][1]
    if restdrink >= wantdrink:
        payment += wantdrink * shoplist[0][0]
        break
    else:
        payment += restdrink * shoplist[0][0]
        wantdrink -= restdrink
        del shoplist[0]
print(payment)

### FIXED CODE ###

# coding: utf-8

data = input().split()
shoplist = []
for i in range(int(data[0])):
    shopdata = list(map(int, input().split()))
    shoplist.append(shopdata)
shoplist.sort()

payment = 0
wantdrink = int(data[1])
while wantdrink > 0 :
    restdrink = shoplist[0][1]
    if restdrink >= wantdrink:
        payment += wantdrink * shoplist[0][0]
        break
    else:
        payment += restdrink * shoplist[0][0]
        wantdrink -= restdrink
        del shoplist[0]
print(payment)
### BUGGY CODE ###

import math
import random
import heapq
from collections import Counter, defaultdict
from decimal import Decimal, ROUND_HALF_UP, ROUND_CEILING
from functools import lru_cache, reduce
from itertools import combinations_with_replacement, product, combinations


def read_int():
    return int(input())


def read_int_n():
    return list(map(int, input().split()))


def read_float():
    return float(input())


def read_float_n():
    return list(map(float, input().split()))


def read_str():
    return input()


def read_str_n():
    return list(map(str, input().split()))


# @lru_cache(size=None)
def slv(S, K):

    if len(S) <= 50:
        d = set([])
        for i in range(len(S)):
            for j in range(i + 1, len(S) + 1):
                d.add(S[i:j])

    # print('-----')

    import bisect
    S_ = [c for c in S]
    # S_.sort()
    idxs = []

    for k in sorted(set(S_)):
        # print('k', k)
        for i in range(len(S)):
            if S[i] == k:
                idxs.append(i)
        d = []

        for i in idxs:
            # print(i)
            for j in range(i + 1, len(S) + 1):
                t = "".join(S[i:j])
                if len(d) > K and d[-1] < t:
                    break
                if t not in d:
                    bisect.insort(d, t)
                    d = d[:K]
        if len(d) >= K:
            break
    print(d)
    return sorted(d)[K - 1]


def main():
    S = read_str()
    K = read_int()
    S = [random.choice('abcdefghijklmnopqrstu') for _ in range(5000)]
    print(slv(S, K))


if __name__ == '__main__':
    main()

### FIXED CODE ###

import math
import random
import heapq
from collections import Counter, defaultdict
from decimal import Decimal, ROUND_HALF_UP, ROUND_CEILING
from functools import lru_cache, reduce
from itertools import combinations_with_replacement, product, combinations


def read_int():
    return int(input())


def read_int_n():
    return list(map(int, input().split()))


def read_float():
    return float(input())


def read_float_n():
    return list(map(float, input().split()))


def read_str():
    return input()


def read_str_n():
    return list(map(str, input().split()))


def slv(S, K):
    d = set([])
    for i in range(len(S)):
        for j in range(i + 1, i + 1 + K):
            d.add(S[i:j])

    return sorted(d)[K - 1]


def main():
    S = read_str()
    K = read_int()
    # K = 3
    # S = ''.join([random.choice('abcdefghijklmnopqrstu') for _ in range(5000)])
    print(slv(S, K))


if __name__ == '__main__':
    main()
### BUGGY CODE ###

import numpy as np
import sys
sys.setrecursionlimit(10**6)
input = sys.stdin.readline

def main():
  H, W = map(int, input().split())
  G = [list(input()) for _ in range(H)]
  black = [[0]*W for _ in range(H)]
  que = []
  ans = 0
  for i in range(H):
    for j in range(W):
      if G[i][j] == '#':
        que.append([i,j])
        black[i][j] = 1
  while que:
    qq = []
    ans += 1
    for nh, nw in que:
      if nw+1<=W-1 and black[nh][nw+1] == 0:
        qq.append([nh,nw+1])
        black[nh][nw+1] = 1
      if  0<=nw-1 and black[nh][nw-1] == 0:
        qq.append([nh,nw-1])
        black[nh][nw-1] = 1
      if nh+1<=H-1 and black[nh+1][nw] == 0:
        qq.append([nh+1,nw])
        black[nh+1][nw] = 1
      if 0<=nh-1 and black[nh-1][nw] == 0:
        qq.append([nh-1,nw])
        black[nh-1][nw] = 1
    que = qq
  print(ans-1)

if __name__ == "__main__":
  main()

### FIXED CODE ###

import copy
from collections import deque
def main():
  H, W = map(int, input().split())
  G = [['#' == x for x in input()] for _ in range(H)]
 
  black = deque([(i, j) for i in range(H) for j in range(W) if G[i][j]])
 
  ans = 0
  while True:
    ans += 1
    next_black = deque()
    while black:
      bi, bj = black.popleft()
      if bi > 0 and not G[bi - 1][bj]:
        G[bi - 1][bj] = True
        next_black.append((bi - 1, bj))
      if bj > 0 and not G[bi][bj - 1]:
        G[bi][bj - 1] = True
        next_black.append((bi, bj - 1))
      if bi < H - 1 and not G[bi + 1][bj]:
        G[bi + 1][bj] = True
        next_black.append((bi + 1, bj))
      if bj < W - 1 and not G[bi][bj + 1]:
        G[bi][bj + 1] = True
        next_black.append((bi, bj + 1))
    if next_black:
       black = copy.copy(next_black)
    else:
       break
  print(ans - 1)
  
if __name__ == "__main__":
  main()
### BUGGY CODE ###

x = 1
y = []
for i in range(1, int(input())+1):
    x = x * i
    y.append(x)
print(max(y)%((10**9)+7))


### FIXED CODE ###

x = 1
for i in range(1, int(input())+1):
    x = x * i
    x = x % (10**9 + 7)
print(x)
### BUGGY CODE ###

from sys import stdin
import sys
import math
from functools import reduce
import functools
import itertools
from collections import deque,Counter
from operator import mul
import copy
# ! /usr/bin/env python
# -*- coding: utf-8 -*-
import heapq

n, k = list(map(int, input().split()))
h = [0] + list(map(int, input().split()))+[0]*(k+10)

INF = 10**10
dp = [INF]*(n+k+10)
dp[1] = 0

for i in range(n+1):
    for j in range(1,k+1):
        a = dp[i] + abs(h[i+j]-h[i])
        if a < dp[i+j]:
            dp[i+j] = a


print(dp[n])



### FIXED CODE ###

from sys import stdin
import sys
import math
from functools import reduce
import functools
import itertools
from collections import deque,Counter
from operator import mul
import copy
# ! /usr/bin/env python
# -*- coding: utf-8 -*-
import heapq

n, k = list(map(int, input().split()))
h = [0] + list(map(int, input().split()))

INF = 10**10
dp = [INF]*(n+5)
dp[1] = 0

for i in range(2,n+1):
    temp = [dp[j] + abs(h[i] - h[j]) for j in range(i-1, max(0,i-k-1), -1)]
    dp[i] = min(temp)

print(dp[n])
### BUGGY CODE ###

A, B, K = map(int, input().split())

count = 0

while count < K:
    if A > 0:
        A -= 1
        count += 1
        continue
        
    if B > 0:
        B -= 1
        count += 1
        continue
        
    if A == 0 and B == 0:
        count += 1
        continue
print(A, B)

### FIXED CODE ###

A, B, K = map(int, input().split())

if A > K:
    print(A-K, B)
if A <= K < A + B:
    print(0, A+B-K)
if A + B <= K:
    print(0, 0)
### BUGGY CODE ###

#
H, W, D = list(map(int, input().split()))
A = []
for i in range(H):
    A.append(list(map(int, input().split())))
Q = int(input())

#
def get_pos(N):
    for y in range(H):
        if N in A[y]:
            x = A[y].index(N)
            return (x+1, y+1)


#
for i in range(Q):
    L, R = list(map(int, input().split()))

    magic = 0
    x, y = get_pos(L)
    #print(x, y)

    while L!=R:
        L += D
        s, t = get_pos(L)
        magic += abs(x-s) + abs(y-t)
        x = s
        y = t

    print(magic)


### FIXED CODE ###

#
H, W, D = list(map(int, input().split()))
A = {}
for y in range(H):
    tmp = list(map(int, input().split()))
    for x in range(W):
        A[tmp[x]] = (x+1, y+1)
Q = int(input())

#
d = [0 for _ in range(H*W)]
for i in range(1, D+1):
    x, y = A[i]

    j = i
    while j+D<=H*W:
        s, t = A[j+D]
        d[j+D-1] = d[j-1] + abs(x-s) + abs(y-t)
        x = s
        y = t
        j += D

#print(d)
for i in range(Q):
    L, R = list(map(int, input().split()))

    print(d[R-1] - d[L-1])
### BUGGY CODE ###

n,u,v=map(int,input().split())
u-=1
v-=1
d=[[]for _ in range(n)]
inf=float('inf')
aoki=[inf]*n
for i in range(n-1):
  a,b=map(int,input().split())
  a-=1
  b-=1
  d[a].append(b)
  d[b].append(a)
Q=d[v]
aoki[v]=0
dis=1
visited={v}
while Q:
  P=[]
  for i in Q:
    visited.add(i)
    for j in d[i]:
      if j not in visited:P.append(j)
    aoki[i]=dis
  dis+=1
  Q=P
chokudai=[-1]*n
chokudai[u]=0
dis=1
cant=set()
Q=d[u]
while Q:
  P=[]
  visited=set()
  for i in Q:
    if i in cant:
      continue
    if dis>=aoki[i]:
      if dis==aoki[i]:chokudai[i]=dis
      cant.add(i)
      continue
    else:
      chokudai[i]=dis
    for j in d[i]:
      if j not in visited:
        P.append(j)
        visited.add(j)
  dis+=1
  Q=P
#ans=0
#for i in range(n):
#  if chokudai[i]!=-1:ans=max(ans,chokudai[i])
#print(ans)
print(max(chokudai))

### FIXED CODE ###

n,u,v=map(int,input().split())
anss=0
u-=1
v-=1
d=[[]for _ in range(n)]
inf=float('inf')
aoki=[inf]*n
for i in range(n-1):
  a,b=map(int,input().split())
  a-=1
  b-=1
  d[a].append(b)
  d[b].append(a)
Q=d[v]
aoki[v]=0
dis=1
visited={v}
while Q:
  P=[]
  for i in Q:
    visited.add(i)
    for j in d[i]:
      if j not in visited:P.append(j)
    aoki[i]=dis
  dis+=1
  Q=P
Q=d[u]
chokudai=[-1]*n
chokudai[u]=0
dis=1
visited={u}
point=-1
while Q:
  P=[]
  for i in Q:
    visited.add(i)
    for j in d[i]:
      if aoki[j]<=dis+1:
        if aoki[j]==dis+1:anss=1
        if point<0:point=i
        continue
      if j not in visited:P.append(j)
    chokudai[i]=dis
  dis+=1
  Q=P
Q=d[point]
dis=chokudai[point]+1
visited={point}
while Q:
  P=[]
  for i in Q:
    visited.add(i)
    if chokudai[i]==-1:continue
    chokudai[i]=max(dis,chokudai[i])
    for j in d[i]:
      if j not in visited:P.append(j)
  dis+=1
  Q=P
ans=0
for i in range(n):
  if aoki[i]>chokudai[i]:ans=max(ans,chokudai[i])
print(ans+anss)
#print(aoki)
#print(chokudai)