You are given a forest — an undirected graph with $n$ vertices such that each its connected component is a tree.

The diameter (aka "longest shortest path") of a connected undirected graph is the maximum number of edges in the shortest path between any pair of its vertices.

You task is to add some edges (possibly zero) to the graph so that it becomes a tree and the diameter of the tree is minimal possible.

If there are multiple correct answers, print any of them.


-----Input-----

The first line contains two integers $n$ and $m$ ($1 \le n \le 1000$, $0 \le m \le n - 1$) — the number of vertices of the graph and the number of edges, respectively.

Each of the next $m$ lines contains two integers $v$ and $u$ ($1 \le v, u \le n$, $v \ne u$) — the descriptions of the edges.

It is guaranteed that the given graph is a forest.


-----Output-----

In the first line print the diameter of the resulting tree.

Each of the next $(n - 1) - m$ lines should contain two integers $v$ and $u$ ($1 \le v, u \le n$, $v \ne u$) — the descriptions of the added edges.

The resulting graph should be a tree and its diameter should be minimal possible.

For $m = n - 1$ no edges are added, thus the output consists of a single integer — diameter of the given tree.

If there are multiple correct answers, print any of them.


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

Output
2
4 2

Input
2 0

Output
1
1 2

Input
3 2
1 3
2 3

Output
2



-----Note-----

In the first example adding edges (1, 4) or (3, 4) will lead to a total diameter of 3. Adding edge (2, 4), however, will make it 2.

Edge (1, 2) is the only option you have for the second example. The diameter is 1.

You can't add any edges in the third example. The diameter is already 2.

Source: codeforces | Difficulty: HARD
Tags: Greedy algorithms

Tree algorithms

Graph traversal

Constructive algorithms


Solutions:
import sys
sys.setrecursionlimit(10000)

class Tree:

	def __init__(self, nodes):
		self.root = None

class Node:

	def __init__(self, val):
		self.parent = None
		self.val = val
		self.children = []

	def add(self, child):
		self.children.append(child)

	def get_max_dist(self, parent, dist):
		max_dist = dist
		for i in self.children:
			if i != parent:
				d = i.get_max_dist(self, dist + 1)
				if max_dist < d:
					max_dist = d
		return max_dist

	def get_dist(self):
		return self.get_max_dist(self, 0)

	def get_count_ch(self, parent):
		count = len(self.children)
		for i in self.children:
			if i != parent:
				count += i.get_count_ch(self) - 1
		return count

	def calc_child(self):
		return (self.get_count_ch(None), len(self.children), self.val)

class Forest:

	def __init__(self, count):
		self.nodes = []
		self.count = count
		self.set_nodes = set()

	def build(self):
		roots = []
		max_dist = []
		list_root = []
		for i in self.nodes:
			tree = list(map(lambda x: x.get_dist(), i))
			ma = max(tree)
			max_dist.append(ma)
			m = i[tree.index(min(tree))]
			roots.append(m)
		if len(roots) > 1:
			ind = max_dist.index(max(max_dist))
			if len(roots) > 1 and ind != 0:
				(roots[0], roots[ind]) = (roots[ind], roots[0])
		s = set()
		for i in self.nodes:
			for j in i:
				s.add(j.val)
		r = list(set(range(1, n + 1)) - s)
		if len(roots) > 0:
			for i in range(1, len(roots)):
				self.add(roots[0].val, roots[i].val)
				list_root.append((roots[0].val, roots[i].val))
			for i in r:
				self.add(roots[0].val, i)
				list_root.append((roots[0].val, i))
		elif len(r) == 1:
			print(0)
			return
		elif len(r) > 1:
			for i in range(1, len(r)):
				self.add(r[0], r[i])
				list_root.append((r[0], r[i]))
		distances = []
		for i in self.nodes[0]:
			dist = i.get_dist()
			distances.append(dist)
		print(max(distances))
		for i in list_root:
			print(*i)

	def add(self, v, u):
		self.set_nodes.add(v)
		self.set_nodes.add(u)
		(v_node, v_list) = self.find(v)
		(u_node, u_list) = self.find(u)
		if v_node == None and u_node == None:
			v_node = Node(v)
			u_node = Node(u)
			v_node.add(u_node)
			u_node.add(v_node)
			self.nodes.append([v_node, u_node])
		elif v_node != None and u_node != None and (v_list != u_list):
			v_node.add(u_node)
			u_node.add(v_node)
			v_list += u_list
			self.nodes.remove(u_list)
		elif v_node == None and u_node != None:
			v_node = Node(v)
			u_node.add(v_node)
			v_node.add(u_node)
			u_list.append(v_node)
		elif v_node != None and u_node == None:
			u_node = Node(u)
			v_node.add(u_node)
			u_node.add(v_node)
			v_list.append(u_node)

	def find(self, value):
		for i_list in self.nodes:
			for i in i_list:
				if i.val == value:
					return (i, i_list)
		return (None, None)
(n, m) = map(int, input().split())
f = Forest(n)
for i in range(m):
	(v, u) = map(int, input().split())
	f.add(v, u)
f.build()


import math
(n, m) = map(int, input().split())
neigh = []
for i in range(n):
	neigh.append([])
for i in range(m):
	(a, b) = map(int, input().split())
	neigh[a - 1].append(b - 1)
	neigh[b - 1].append(a - 1)
seen = set()
index = [0] * n
diams = []
trees = 0
for i in range(n):
	if i not in seen:
		trees += 1
		index[i] = trees
		seen.add(i)
		layer = [i]
		prev = None
		pars = [None]
		while layer != []:
			newlayer = []
			newpars = []
			for i in range(len(layer)):
				vert = layer[i]
				par = pars[i]
				for child in neigh[vert]:
					if child != par:
						newlayer.append(child)
						newpars.append(vert)
						index[child] = trees
						seen.add(child)
			prev = layer
			layer = newlayer
			pars = newpars
		far = prev[0]
		layer = [[far]]
		pars = [None]
		prev = None
		while layer != []:
			newlayer = []
			newpars = []
			for i in range(len(layer)):
				vert = layer[i][-1]
				par = pars[i]
				for child in neigh[vert]:
					if child != par:
						newlayer.append(layer[i] + [child])
						newpars.append(vert)
			prev = layer
			layer = newlayer
			pars = newpars
		diam = prev[0]
		lent = len(diam)
		mid = diam[lent // 2]
		diams.append((lent - 1, mid))
diams.sort(reverse=True)
poss = [diams[0][0]]
if len(diams) > 1:
	poss.append(math.ceil(diams[0][0] / 2) + 1 + math.ceil(diams[1][0] / 2))
if len(diams) > 2:
	poss.append(math.ceil(diams[1][0] / 2) + 2 + math.ceil(diams[2][0] / 2))
print(max(poss))
cent = diams[0][1]
for i in range(len(diams) - 1):
	print(cent + 1, diams[i + 1][1] + 1)


from collections import defaultdict, deque
from math import ceil
(n, m) = map(int, input().split())
graph = defaultdict(list)
for i in range(m):
	(u, v) = map(int, input().split())
	graph[u].append(v)
	graph[v].append(u)
vis = set()
diams = []
for node in range(1, n + 1):
	if node not in vis:
		vis.add(node)
		q = deque()
		cur_big = 0
		cur_big_node = node
		q.append((node, node, 0))
		while q:
			(pro_n, par, val) = q.popleft()
			for child in graph[pro_n]:
				if child != par:
					vis.add(child)
					q.append((child, pro_n, val + 1))
			if val > cur_big:
				cur_big = val
				cur_big_node = pro_n
		diameter = 0
		end_node = cur_big_node
		q.append((cur_big_node, cur_big_node, 0))
		pa = defaultdict(int)
		while q:
			(pro_n, par, val) = q.popleft()
			pa[pro_n] = par
			for child in graph[pro_n]:
				if child != par:
					q.append((child, pro_n, val + 1))
			if val > diameter:
				diameter = val
				end_node = pro_n
		cen_node = end_node
		for i in range(diameter // 2):
			cen_node = pa[cen_node]
		diams.append((diameter, cen_node))
diams.sort(reverse=True)
if len(diams) > 2:
	if diams[0][0] == diams[1][0] == diams[2][0]:
		res = ceil(diams[0][0] / 2) + ceil(diams[1][0] / 2) + 2
	else:
		res = max(diams[0][0], ceil(diams[0][0] / 2) + ceil(diams[1][0] / 2) + 1)
elif len(diams) >= 2:
	res = max(diams[0][0], ceil(diams[0][0] / 2) + ceil(diams[1][0] / 2) + 1)
else:
	res = diams[0][0]
print(res)
for i in range(1, len(diams)):
	print(diams[0][1], diams[i][1])


import sys
sys.setrecursionlimit(1100)

def dfs1(u, pre):
	vis[u] = True
	now.append(u)
	for v in to[u]:
		if v != pre:
			dfs1(v, u)

def dfs2(u, pre):
	mxdist[u] = dist[u]
	for v in to[u]:
		if v != pre:
			dist[v] = dist[u] + 1
			dfs2(v, u)
			mxdist[u] = max(mxdist[u], mxdist[v])
try:
	lab = 1
	(n, m) = [int(x) for x in input().split()]
	to = [[] for i in range(n + 10)]
	dist = [0 for i in range(n + 10)]
	mxdist = [0 for i in range(n + 10)]
	lab = 2
	for i in range(m):
		(u, v) = [int(x) for x in input().split()]
		to[u].append(v)
		to[v].append(u)
	com = []
	vis = [False for i in range(n + 10)]
	for i in range(1, n + 1):
		if vis[i] == False:
			now = []
			dfs1(i, 0)
			com.append(now)
	lab = 3
	ct = []
	mx = 0
	for lis in com:
		tmp = []
		d = 0
		for root in lis:
			for u in lis:
				dist[u] = mxdist[u] = 0
			dfs2(root, 0)
			tmp.append((mxdist[root], root))
			d = max(d, sum(sorted([mxdist[u] for u in to[root]])[-2:]))
		mx = max(mx, d)
		for x in tmp:
			if x[0] == (d + 1) // 2:
				center = [x[1] for x in tmp if x[0] == (d + 1) // 2][0]
		ct.append(((d + 1) // 2, center))
	lab = 4
	ct.sort(reverse=True)
	ans = []
	for i in range(1, len(ct)):
		mx = max(mx, ct[i][0] + 1 + ct[0][0])
		if i > 1:
			mx = max(mx, ct[i][0] + 2 + ct[1][0])
		ans.append((ct[i][1], ct[0][1]))
	print(mx)
	for p in ans:
		print(*p)
except Exception as e:
	print('error after lable', lab, ', type =', e)


from collections import defaultdict
from collections import deque
import heapq
import sys
input = sys.stdin.readline

def get_root(s):
	v = []
	while not s == root[s]:
		v.append(s)
		s = root[s]
	for i in v:
		root[i] = s
	return s

def unite(s, t):
	(rs, rt) = (get_root(s), get_root(t))
	if not rs ^ rt:
		return
	if rank[s] == rank[t]:
		rank[rs] += 1
	if rank[s] >= rank[t]:
		root[rt] = rs
		size[rs] += size[rt]
	else:
		root[rs] = rt
		size[rt] += size[rs]
	return

def same(s, t):
	return True if get_root(s) == get_root(t) else False

def bfs(r):
	q = deque()
	q.append(r)
	dist1[r] = 0
	(m0, u) = (0, r)
	while q:
		i = q.popleft()
		di = dist1[i]
		if m0 < di:
			m0 = di
			u = i
		for j in G[i]:
			if dist1[j] == -1:
				dist1[j] = di + 1
				q.append(j)
	q.append(u)
	dist2[u] = 0
	(m0, v) = (0, u)
	while q:
		i = q.popleft()
		di = dist2[i]
		if m0 < di:
			m0 = di
			v = i
		for j in G[i]:
			if dist2[j] == -1:
				dist2[j] = di + 1
				q.append(j)
	q.append(v)
	dist3[v] = 0
	while q:
		i = q.popleft()
		di = dist3[i]
		for j in G[i]:
			if dist3[j] == -1:
				dist3[j] = di + 1
				q.append(j)
	c = r
	ma = m0
	for i in x[r]:
		m1 = max(dist2[i], dist3[i])
		if m1 < ma:
			(ma, c) = (m1, i)
	return (ma, m0, c)
(n, m) = map(int, input().split())
G = [[] for _ in range(n + 1)]
root = [i for i in range(n + 1)]
rank = [1 for _ in range(n + 1)]
size = [1 for _ in range(n + 1)]
for _ in range(m):
	(u, v) = map(int, input().split())
	unite(u, v)
	G[u].append(v)
	G[v].append(u)
x = defaultdict(lambda : [])
s = set()
for i in range(1, n + 1):
	r = get_root(i)
	x[r].append(i)
	s.add(r)
dist1 = [-1] * (n + 1)
dist2 = [-1] * (n + 1)
dist3 = [-1] * (n + 1)
h = []
l = 0
for i in s:
	(ma, m0, c) = bfs(i)
	l = max(l, m0)
	heapq.heappush(h, (-ma, c))
(s, t) = ([], [])
while h:
	(m0, c) = heapq.heappop(h)
	s.append(-m0)
	t.append(c)
ans = l
for i in range(len(s)):
	si = s[i]
	for j in range(i + 1, len(s)):
		sj = s[j]
		ans = max(ans, si + sj + min(i, 1) + 1)
print(ans)
u = t[0]
for i in range(1, len(t)):
	v = t[i]
	print(u, v)


from collections import deque
(n, m) = [int(x) for x in input().split()]
tree = {}
for i in range(m):
	(a, b) = [int(x) for x in input().split()]
	if a not in tree:
		tree[a] = [b]
	else:
		tree[a].append(b)
	if b not in tree:
		tree[b] = [a]
	else:
		tree[b].append(a)
for i in range(1, n + 1):
	if i not in tree:
		tree[i] = []

def solve(node):
	from collections import deque

	def bfs(graph, currnode):
		visited = [False for x in range(n + 1)]
		stack = deque()
		ans = []
		stack.append(currnode)
		d = 0
		while stack:
			currnode = stack.popleft()
			ans.append(currnode)
			if visited[currnode] == False:
				visited[currnode] = True
			for neigbour in graph[currnode]:
				if visited[neigbour] == False:
					visited[neigbour] = True
					stack.append(neigbour)
		return ans[-1]
	node1 = bfs(tree, node)
	node2 = bfs(tree, node1)

	def bfs_dis(graph, a, b):
		visited = [False for x in range(n + 1)]
		stack = deque()
		stack.append((a, 0))
		while stack:
			(currnode, d) = stack.popleft()
			if visited[currnode] == False:
				visited[currnode] = True
			if currnode == b:
				return (d, visited)
			for neigbour in graph[currnode]:
				if visited[neigbour] == False:
					visited[neigbour] = True
					stack.append((neigbour, d + 1))
		return None
	return (bfs_dis(tree, node1, node2), node1, node2)
visited = [False for x in range(n + 1)]
arr = []
for node in range(1, n + 1):
	if visited[node] == False:
		(k, node1, node2) = solve(node)
		(d, visited) = k
		arr.append([d, node1, node2])
arr.sort()
ans = [0 for x in range(len(arr))]

def dfs(node1, node2, graph):
	visited = [False for x in range(n + 1)]
	stack = [node1]
	index = [0 for x in range(n + 1)]
	while stack:
		currnode = stack[-1]
		if currnode == node2:
			mid = len(stack) // 2
			return stack[mid]
		if visited[currnode] == False:
			visited[currnode] = True
		for i in range(index[currnode], len(graph[currnode])):
			neighbour = graph[currnode][i]
			if visited[neighbour] == False:
				visited[neighbour] = True
				stack.append(neighbour)
				index[currnode] += 1
				break
		else:
			stack.pop()
	return
for i in range(len(arr)):
	if arr[i][0] == 0:
		arr[i][0] += 1
	(d, node1, node2) = arr[i]
	mid = dfs(node1, node2, tree)
	ans[i] = mid
for i in range(len(ans) - 1):
	tree[ans[-1]].append(ans[i])
	tree[ans[i]].append(ans[-1])
	ans[i] = (ans[i], ans[-1])
(k, n1, n2) = solve(1)
(d, visited) = k
print(d)
for i in range(len(ans) - 1):
	print(*ans[i])


import sys

def dfs(v, d, prev, i):
	global mid
	global M
	M[v] = False
	way[d] = v
	if way[d + 1] == 0:
		mid[i] = way[d // 2]
	mx = (d, v)
	for x in E[v]:
		if x != prev:
			mx = max(mx, dfs(x, d + 1, v, i))
	return mx
sys.setrecursionlimit(2000)
(n, m) = map(int, input().split())
E = [[] for i in range(n + 1)]
for i in range(m):
	(a, b) = map(int, input().split())
	E[a].append(b)
	E[b].append(a)
mid = [0] * (n + 2)
c = 0
k = 0
way = [0] * (n + 2)
M = [True] * (n + 1)
M[0] = False
i = -1
while True in M:
	i += 1
	idx = M.index(True)
	p1 = dfs(idx, 0, 0, i)[1]
	way = [0] * (n + 2)
	(s, p2) = dfs(p1, 0, 0, i)
	if s > c:
		c = s
		k = i
r = []
for j in range(0, i + 1):
	if j == k:
		continue
	r.append((mid[k], mid[j]))
	E[mid[k]].append(mid[j])
	E[mid[j]].append(mid[k])
p1 = dfs(1, 0, 0, n + 1)[1]
(s, p2) = dfs(p1, 0, 0, n + 1)
print(s)
for item in r:
	print(item[0], item[1])