Further research on zombie thought processes yielded interesting results. As we know from the previous problem, the nervous system of a zombie consists of n brains and m brain connectors joining some pairs of brains together. It was observed that the intellectual abilities of a zombie depend mainly on the topology of its nervous system. More precisely, we define the distance between two brains u and v (1 ≤ u, v ≤ n) as the minimum number of brain connectors used when transmitting a thought between these two brains. The brain latency of a zombie is defined to be the maximum distance between any two of its brains. Researchers conjecture that the brain latency is the crucial parameter which determines how smart a given zombie is. Help them test this conjecture by writing a program to compute brain latencies of nervous systems.

In this problem you may assume that any nervous system given in the input is valid, i.e., it satisfies conditions (1) and (2) from the easy version.


-----Input-----

The first line of the input contains two space-separated integers n and m (1 ≤ n, m ≤ 100000) denoting the number of brains (which are conveniently numbered from 1 to n) and the number of brain connectors in the nervous system, respectively. In the next m lines, descriptions of brain connectors follow. Every connector is given as a pair of brains a b it connects (1 ≤ a, b ≤ n and a ≠ b).


-----Output-----

Print one number – the brain latency.


-----Examples-----
Input
4 3
1 2
1 3
1 4

Output
2
Input
5 4
1 2
2 3
3 4
3 5

Output
3

Source: codeforces | Difficulty: MEDIUM
Tags: Tree algorithms

Graph algorithms

Graph traversal


Solutions:
import sys
arr = list(map(int, input().split()))
n = arr[0]
m = arr[1]
graph = [[] for _ in range(n)]
graph2 = [[] for _ in range(n)]
for i in range(n - 1):
	inf = list(map(int, input().split()))
	v1 = inf[0] - 1
	v2 = inf[1] - 1
	graph2[v1].append(v2)
	graph2[v2].append(v1)
	graph[v1].append(v2)
	graph[v2].append(v1)
curr = [0, 0]
stk = []
nvis = [True] * n
ans = 0
dis = 0
pt = 0
while True:
	nxt = -1
	temp = len(graph[curr[0]])
	for i in range(temp - 1, -1, -1):
		if nvis[graph[curr[0]][i]]:
			nxt = graph[curr[0]][i]
			break
		else:
			graph[curr[0]].pop()
	if nxt != -1:
		stk.append([curr[0], curr[1]])
		nvis[curr[0]] = False
		curr = [nxt, curr[1] + 1]
	else:
		if curr[0] == 0:
			break
		nvis[curr[0]] = False
		if dis < curr[1]:
			dis = curr[1]
			pt = curr[0]
		curr = stk[-1]
		stk.pop(-1)
init = pt
graph = graph2
curr = [pt, 0]
stk = []
nvis = [True] * n
ans = 0
dis = 0
pt = 0
while True:
	nxt = -1
	temp = len(graph[curr[0]])
	for i in range(temp - 1, -1, -1):
		if nvis[graph[curr[0]][i]]:
			nxt = graph[curr[0]][i]
			break
		else:
			graph[curr[0]].pop()
	if nxt != -1:
		stk.append([curr[0], curr[1]])
		nvis[curr[0]] = False
		curr = [nxt, curr[1] + 1]
	else:
		if curr[0] == init:
			break
		nvis[curr[0]] = False
		if dis < curr[1]:
			dis = curr[1]
			pt = curr[0]
		curr = stk[-1]
		stk.pop(-1)
print(dis)


import sys
from collections import defaultdict
(n, m) = list(map(int, sys.stdin.readline().lstrip().rstrip().split()))
graph = defaultdict(list)
for i in range(m):
	(u, v) = list(map(int, sys.stdin.readline().lstrip().rstrip().split()))
	graph[u - 1].append(v - 1)
	graph[v - 1].append(u - 1)
visited = [False for i in range(n)]
q = [[0, 0]]
temp = []
visited[0] = True
while q != []:
	(node, dist) = (q[0][0], q[0][1])
	q.pop(0)
	leaf = True
	for v in graph[node]:
		if visited[v] == False:
			visited[v] = True
			q.append([v, dist + 1])
			leaf = False
	if leaf:
		temp.append([dist, node])
temp.sort()
visited = [False for i in range(n)]
q = [[temp[-1][1], 0]]
temp = []
visited[q[0][0]] = True
while q != []:
	(node, dist) = (q[0][0], q[0][1])
	q.pop(0)
	leaf = True
	for v in graph[node]:
		if visited[v] == False:
			visited[v] = True
			q.append([v, dist + 1])
			leaf = False
	if leaf:
		temp.append(dist)
sys.stdout.write(str(max(temp)) + '\n')


(n, m) = list(map(int, input().split()))
from collections import defaultdict, deque
g = defaultdict(list)
for i in range(m):
	(a, b) = list(map(int, input().split()))
	g[a - 1].append(b - 1)
	g[b - 1].append(a - 1)

def dfs(x):
	vis[x] = 1
	q = deque()
	q.append((x, 0))
	while q:
		(cur, d) = q.popleft()
		if maxd[0] < d:
			maxd[0] = d
			maxnode[0] = cur
		for i in g[cur]:
			if vis[i] == 0:
				q.append((i, d + 1))
				vis[i] = 1
vis = [0] * n
maxd = [0]
maxnode = [0]
dfs(0)
vis = [0] * n
maxd = [0]
dfs(maxnode[0])
print(maxd[0])


import sys
with sys.stdin as f:
	for (i, line) in enumerate(f):
		if i == 0:
			(N, M) = line.split(' ')
			(N, M) = (int(N), int(M))
			graph = [[] for _ in range(N)]
		else:
			(fromVertex, toVertex) = line.split(' ')
			(fromVertex, toVertex) = (int(fromVertex) - 1, int(toVertex) - 1)
			graph[fromVertex].append(toVertex)
			graph[toVertex].append(fromVertex)
from queue import Queue

def farthest_node_distance(start_node, graph):
	N = len(graph)
	visited = [False for _ in range(N)]
	distances = [-1 for _ in range(N)]
	visited[start_node] = True
	distances[start_node] = 0
	nodes_queue = Queue()
	nodes_queue.put(start_node)
	while not nodes_queue.empty():
		node = nodes_queue.get()
		for neigh in graph[node]:
			if not visited[neigh]:
				visited[neigh] = True
				distances[neigh] = distances[node] + 1
				nodes_queue.put(neigh)
	return (node, distances[node])
(u, dist_u) = farthest_node_distance(0, graph)
(v, dist_uv) = farthest_node_distance(u, graph)
print(dist_uv)


import copy
import sys
import threading
threading.stack_size(64 * 1024 * 1024)
sys.setrecursionlimit(10 ** 6)
(n, m) = map(int, input().split())
ans = 0
sz = [0] * (n + 1)
graph = []
for _ in range(n + 1):
	graph.append([])
for _ in range(m):
	(u, v) = map(int, input().split())
	graph[u].append(v)
	graph[v].append(u)

def dfs(v, pr):
	nonlocal ans
	for to in graph[v]:
		if to != pr:
			dfs(to, v)
	if pr != -1:
		ans = max(ans, sz[pr] + sz[v])
		sz[pr] = max(sz[pr], sz[v] + 1)

def main():
	dfs(1, -1)
	print(ans + 1)
th = threading.Thread(target=main)
th.start()


f = lambda : map(int, input().split())
(n, m) = f()
p = [[] for i in range(n)]
for j in range(m):
	(a, b) = f()
	p[a - 1].append(b - 1)
	p[b - 1].append(a - 1)

def g(i):
	(u, t) = ([1] * n, (0, i))
	s = [t]
	while s:
		(d, i) = s.pop()
		u[i] = 0
		if d > t[0]:
			t = (d, i)
		s += [(d + 1, j) for j in p[i] if u[j]]
	return t
print(g(g(0)[1])[0])


def bfs(x, g):
	(n, q) = (len(g), [x])
	dist = [0 if y == x else -1 for y in range(n)]
	i = 0
	while i < len(q):
		v = q[i]
		i += 1
		for to in g[v]:
			if dist[to] < 0:
				dist[to] = dist[v] + 1
				q.append(to)
	return (q[-1], dist[q[-1]])
(n, m) = map(int, input().split())
g = [[] for _ in range(n)]
for _ in range(m):
	(a, b) = map(lambda x: int(x) - 1, input().split())
	g[a].append(b)
	g[b].append(a)
print(bfs(bfs(0, g)[0], g)[1])


import sys
input = sys.stdin.readline
from collections import deque
t = 1
import math

def bfs(a, i, dis, vis):
	vis[i] = 1
	pp = deque()
	pp.append(i)
	while len(pp) != 0:
		z = pp[0]
		vis[z] = 1
		pp.popleft()
		for j in a[z]:
			if vis[j] == 0:
				dis[j] = dis[z] + 1
				pp.append(j)
while t > 0:
	t -= 1
	(n, m) = map(int, input().split())
	a = [[] for i in range(n + 1)]
	for i in range(m):
		(x, y) = map(int, input().split())
		a[x].append(y)
		a[y].append(x)
	vis = [0 for i in range(n + 1)]
	dis = [0 for i in range(n + 1)]
	bfs(a, 1, dis, vis)
	p = [max(dis), dis.index(max(dis))]
	vis = [0 for i in range(n + 1)]
	dis = [0 for i in range(n + 1)]
	bfs(a, p[1], dis, vis)
	p = [max(dis), dis.index(max(dis))]
	print(p[0])


(n, m) = map(int, input().split())
cn = {}
for i in range(1, n + 1):
	cn[i] = set()
for _ in range(m):
	(a, b) = map(int, input().split())
	cn[a].add(b)
	cn[b].add(a)

def dfs(node):
	vs = set()
	q = [(0, node)]
	dist = 0
	fnode = node
	while q:
		(d, node) = q.pop()
		vs.add(node)
		if d > dist:
			(dist, fnode) = (d, node)
		for i in cn[node]:
			if i not in vs:
				q.append((d + 1, i))
	return (dist, fnode)
(_, fnode) = dfs(1)
print(dfs(fnode)[0])


import os
import sys
from io import BytesIO, IOBase
BUFSIZE = 8192

class FastIO(IOBase):
	newlines = 0

	def __init__(self, file):
		self._fd = file.fileno()
		self.buffer = BytesIO()
		self.writable = 'x' in file.mode or 'r' not in file.mode
		self.write = self.buffer.write if self.writable else None

	def read(self):
		while True:
			b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
			if not b:
				break
			ptr = self.buffer.tell()
			(self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr))
		self.newlines = 0
		return self.buffer.read()

	def readline(self):
		while self.newlines == 0:
			b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
			self.newlines = b.count(b'\n') + (not b)
			ptr = self.buffer.tell()
			(self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr))
		self.newlines -= 1
		return self.buffer.readline()

	def flush(self):
		if self.writable:
			os.write(self._fd, self.buffer.getvalue())
			(self.buffer.truncate(0), self.buffer.seek(0))

class IOWrapper(IOBase):

	def __init__(self, file):
		self.buffer = FastIO(file)
		self.flush = self.buffer.flush
		self.writable = self.buffer.writable
		self.write = lambda s: self.buffer.write(s.encode('ascii'))
		self.read = lambda : self.buffer.read().decode('ascii')
		self.readline = lambda : self.buffer.readline().decode('ascii')
(sys.stdin, sys.stdout) = (IOWrapper(sys.stdin), IOWrapper(sys.stdout))
input = lambda : sys.stdin.readline().rstrip('\r\n')
from collections import Counter
from types import GeneratorType

def iterative(f, stack=[]):

	def wrapped_func(*args, **kwargs):
		if stack:
			return f(*args, **kwargs)
		to = f(*args, **kwargs)
		while True:
			if type(to) is GeneratorType:
				stack.append(to)
				to = next(to)
				continue
			stack.pop()
			if not stack:
				break
			to = stack[-1].send(to)
		return to
	return wrapped_func
ans = 0
node = 1

@iterative
def dfs(s, h):
	global ans
	global node
	v[s] = 1
	if h > ans:
		ans = h
		node = s
	for i in g[s]:
		if v[i] == 0:
			ok = (yield dfs(i, h + 1))
	yield True
(n, k) = map(int, input().split())
g = [[] for i in range(n + 1)]
for _ in range(k):
	(u, v) = map(int, input().split())
	g[u].append(v)
	g[v].append(u)
v = [0] * (n + 1)
dfs(1, 0)
v = [0] * (n + 1)
ans = 0
dfs(node, 0)
print(ans)


__import__('sys').setrecursionlimit(10 ** 6)
import threading
threading.stack_size(64 * 1024 * 1024)

def dfs(u, h, par, tr, arr):
	arr[u] = h
	for v in tr[u]:
		if v != par:
			dfs(v, h + 1, u, tr, arr)

def longpathv(tr, v):
	n = len(tr)
	arr = [0] * n
	dfs(v, 0, -1, tr, arr)
	ans = max(range(n), key=lambda x: arr[x])
	return (ans, arr[ans])

def longpath(tr):
	return longpathv(tr, longpathv(tr, 0)[0])[1]

def main(tr):
	print(longpath(tr))
(n, m) = map(int, input().split())
tr = [[] for i in range(n)]
for i in range(m):
	(a, b) = map(int, input().split())
	a -= 1
	b -= 1
	tr[a].append(b)
	tr[b].append(a)
th = threading.Thread(target=main, args=tuple([tr]))
th.start()


import sys

def find_farest_v(v, g):
	queue_v = [(v, 0)]
	order = []
	visited_v = set()
	while queue_v:
		(current_v, dist) = queue_v.pop(0)
		visited_v.add(current_v)
		order.append((current_v, dist))
		for neib in adj_graph[current_v]:
			if neib not in visited_v:
				queue_v.append((neib, dist + 1))
	return order[-1]
(n, m) = list(map(int, input().strip().split(' ')))
adj_graph = [[] for i in range(n)]
for i in range(m):
	line = input()
	(v1, v2) = list(map(int, line.split(' ')))
	adj_graph[v1 - 1].append(v2 - 1)
	adj_graph[v2 - 1].append(v1 - 1)
(v1, d1) = find_farest_v(0, adj_graph)
(v2, d2) = find_farest_v(v1, adj_graph)
print(d2)


(n, m) = map(int, input().split())
gr = [[] for i in range(n)]
for i in range(m):
	(u, v) = map(int, input().split())
	gr[v - 1].append(u - 1)
	gr[u - 1].append(v - 1)
v = [False for i in range(n)]
s = [0]
tr = {}
tr[0] = 0
while s:
	x = s.pop()
	v[x] = True
	for j in gr[x]:
		if v[j]:
			continue
		s.append(j)
		tr[j] = tr[x] + 1
va = 0
ma = 0
for j in tr.keys():
	if ma < tr[j]:
		ma = tr[j]
		va = j
v = [False for i in range(n)]
s = [va]
tr = {}
tr[va] = 0
while s:
	x = s.pop()
	v[x] = True
	for i in gr[x]:
		if v[i]:
			continue
		s.append(i)
		tr[i] = tr[x] + 1
print(max(tr.values()))