The Dogeforces company has $k$ employees. Each employee, except for lower-level employees, has at least $2$ subordinates. Lower-level employees have no subordinates. Each employee, except for the head of the company, has exactly one direct supervisor. The head of the company is a direct or indirect supervisor of all employees. It is known that in Dogeforces, each supervisor receives a salary strictly more than all his subordinates.

The full structure of the company is a secret, but you know the number of lower-level employees and for each pair of lower-level employees, the salary of their common supervisor is known (if there are several such supervisors, then the supervisor with the minimum salary). You have to restore the structure of the company.


-----Input-----

The first line contains a single integer $n$ ($2 \le n \le 500$) — the number of lower-level employees.

This is followed by $n$ lines, where $i$-th line contains $n$ integers $a_{i,1}, a_{i,2}, \dots, a_{i,n}$ ($1 \le a_{i,j} \le 5000$) — salary of the common supervisor of employees with numbers $i$ and $j$. It is guaranteed that $a_{i,j} = a_{j,i}$. Note that $a_{i,i}$ is equal to the salary of the $i$-th employee.


-----Output-----

In the first line, print a single integer $k$ — the number of employees in the company.

In the second line, print $k$ integers $c_1, c_2, \dots, c_k$, where $c_i$ is the salary of the employee with the number $i$.

In the third line, print a single integer $r$ — the number of the employee who is the head of the company.

In the following $k-1$ lines, print two integers $v$ and $u$ ($1 \le v, u \le k$) — the number of the employee and his direct supervisor.

Note that the lower-level employees have numbers from $1$ to $n$, and for the rest of the employees, you have to assign numbers from $n+1$ to $k$. If there are several correct company structures, you can print any of them.


-----Examples-----

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


-----Note-----

One of the possible structures in the first example:

Difficulty: HARD
Tags: Graph traversal

Constructive algorithms

Sorting

Greedy algorithms

Tree algorithms

Divide and conquer

Spanning trees

Data structures
Skill types: Sorting

Data structures

Greedy algorithms

Starter code:

Solutions:
import collections
t = int(input())
a = [None for _ in range(t)]
res = []
parents = []
for i in range(t):
	a[i] = list(map(int, input().split()))
	res.append(a[i][i])

def split(ids):
	if len(ids) == 1:
		return ids[0] + 1
	groups = []
	d = set(ids)
	mx = max([x for (i, x) in enumerate(a[ids[0]]) if i in d])
	res.append(mx)
	cur = len(res)
	for id in ids:
		found = False
		for group in groups:
			if a[group[0]][id] < mx:
				group.append(id)
				found = True
				break
		if not found:
			groups.append([id])
	for group in groups:
		parents.append([split(group), cur])
	return cur
chief = split([i for i in range(t)])
print(len(res))
print(*res, sep=' ')
print(chief)
for r in parents:
	print(*r, sep=' ')


n = 3
pairs = [[2, 5, 7], [5, 1, 7], [7, 7, 4]]
n = int(input())
pairs = [[None for _ in range(n)] for _ in range(n)]
for i in range(n):
	pairs[i] = [int(x) for x in input().split(' ')]
salaries = [pairs[i][i] for i in range(n)]
report_sets = [[i] for i in range(n)]
done = [False for _ in range(n)]
boss = None
relationships = []
report_sets_to_indices = {}
while True:
	index = None
	for (i, d) in enumerate(done):
		if not d:
			index = i
			break
	if index is None:
		break
	done[index] = True
	reports = report_sets[index]
	salary = salaries[index]
	direct_manager_salary = min([x for x in pairs[reports[0]] if x > salary])
	direct_manager_reports = tuple((x for x in range(n) if pairs[reports[0]][x] <= direct_manager_salary))
	if direct_manager_reports not in report_sets_to_indices:
		salaries.append(direct_manager_salary)
		report_sets.append(direct_manager_reports)
		report_sets_to_indices[direct_manager_reports] = len(salaries)
		if len(direct_manager_reports) == n:
			boss = len(salaries)
			done.append(True)
		else:
			done.append(False)
	relationships.append((index + 1, report_sets_to_indices[direct_manager_reports]))
print(len(salaries))
print(' '.join([str(x) for x in salaries]))
print(boss)
for r in relationships:
	print('{} {}'.format(r[0], r[1]))


import os
import sys
from io import BytesIO, IOBase
import threading
from bisect import bisect_right
from math import gcd, log
from collections import Counter
from pprint import pprint
from itertools import permutations
from bisect import bisect_right, bisect_left

def main():
	n = int(input())
	mat = [[0] * n for i in range(n)]
	inc = [[] for i in range(50001)]
	rpr = [i for i in range(n)]
	c = [0] * 10 ** 6
	for i in range(n):
		mat[i] = list(map(int, input().split()))
		for j in range(n):
			inc[mat[i][j]].append((i, j))
			if i == j:
				c[i] = mat[i][j]
	new = n
	st = set()
	newedg = set()
	for i in range(5001):
		groups = []
		for (x, y) in inc[i]:
			if x != y:
				bol = True
				for g in groups:
					if y in g:
						g.add(x)
						bol = False
					if x in g:
						g.add(y)
						bol = False
				if bol:
					groups.append({x, y})
		for g in groups:
			for node in g:
				(a, b) = (min(rpr[node], new), max(rpr[node], new))
				newedg.add((a, b))
				rpr[node] = new
			c[new] = i
			new += 1
	print(new)
	print(*c[:new])
	print(new)
	for (a, b) in newedg:
		print(a + 1, b + 1)
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')
for _ in range(1):
	main()


import io
import os
input = io.BytesIO(os.read(0, os.fstat(0).st_size)).readline

class DSU:

	def __init__(self, n):
		self.parent = list(range(n))

	def add(self):
		n = len(self.parent)
		self.parent.append(n)
		return n

	def find(self, v):
		if v == self.parent[v]:
			return v
		self.parent[v] = self.find(self.parent[v])
		return self.parent[v]

	def union(self, a, b):
		a = self.find(a)
		b = self.find(b)
		if a != b:
			parent[b] = a

def solve():
	n = int(input())
	vals = []
	dsu = DSU(n)
	par = [-1] * n
	g = []
	all_vals = []
	for i in range(n):
		ai = list(map(int, input().split()))
		vals.append(ai[i])
		g.append(ai)
		for j in range(i + 1, n):
			all_vals.append((ai[j], i, j))
	all_vals.sort()
	for (val, i, j) in all_vals:
		if dsu.find(i) == dsu.find(j):
			continue
		if vals[dsu.find(i)] != val:
			new = dsu.add()
			vals.append(val)
			par.append(-1)
			par[dsu.find(i)] = new
			dsu.parent[dsu.find(i)] = new
		par[dsu.find(j)] = new
		dsu.parent[dsu.find(j)] = new
	print(len(vals))
	print(*vals)
	print(len(vals))
	for i in range(len(vals) - 1):
		print(i + 1, par[i] + 1)
t = 1
for _ in range(t):
	solve()


import os, sys, heapq as h, time
from io import BytesIO, IOBase
from types import GeneratorType
from bisect import bisect_left, bisect_right
from collections import defaultdict as dd, deque as dq, Counter as dc
import math, string
BUFSIZE = 8192

class FastIO(IOBase):
	newlines = 0

	def __init__(self, file):
		import os
		self.os = os
		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 = self.os.read(self._fd, max(self.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 = self.os.read(self._fd, max(self.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:
			self.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')

def getInt():
	return int(input())

def getStrs():
	return input().split()

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

def getStr():
	return input()

def listStr():
	return list(input())

def getMat(n):
	return [getInts() for _ in range(n)]

def isInt(s):
	return '0' <= s[0] <= '9'
MOD = 10 ** 9 + 7

def solve():
	N = getInt()
	M = getMat(N)
	parent = [-1] * N
	salary = [-1] * N
	lookup = dd(int)
	for i in range(N):
		salary[i] = M[i][i]
		to_join = -1
		lowest = 10 ** 4
		for j in range(i):
			if M[i][j] < lowest:
				lowest = M[i][j]
				to_join = j
		if i == 0:
			prev = 0
			B = sorted([(a, j) for (j, a) in enumerate(M[0])])
			for j in range(1, N):
				if B[j][0] == B[j - 1][0]:
					lookup[i, s] = prev
				else:
					idx = len(parent)
					s = B[j][0]
					lookup[i, s] = idx
					parent.append(-1)
					parent[prev] = idx
					salary.append(s)
					prev = idx
		else:
			assert to_join >= 0
			prev = i
			flag = False
			B = sorted([(a, j) for (j, a) in enumerate(M[i])])
			for j in range(1, N):
				if B[j][0] == lowest:
					idx = lookup[to_join, lowest]
					lookup[i, lowest] = idx
					parent[prev] = idx
					flag = True
				elif B[j][0] != B[j - 1][0] and (not flag):
					idx = len(parent)
					s = B[j][0]
					lookup[i, s] = idx
					parent.append(-1)
					parent[prev] = idx
					salary.append(s)
					prev = idx
				elif not flag:
					lookup[i, s] = prev
				else:
					lookup[i, s] == lookup[to_join, s]
	print(len(parent))
	print(*salary)
	for (i, p) in enumerate(parent):
		if p == -1:
			print(i + 1)
	for (i, p) in enumerate(parent):
		if p == -1:
			continue
		print(i + 1, p + 1)
	return
solve()


import sys
input = sys.stdin.readline
n = int(input())
low = []
lowsup = [0] * n
for i in range(n):
	lowsup[i] = []
high = []
highsub = []
inp = []
for i in range(n):
	inp.append(list(map(int, input().split())))
for i in range(n):
	sal = []
	for j in range(n):
		sal.append([inp[i][j], j])
	sal.sort()
	low.append(sal[0][0])
	alr = set()
	for x in lowsup[i]:
		alr.add(high[x])
	isnew = True
	for j in range(1, n):
		if not isnew:
			break
		if sal[j][0] > sal[j - 1][0]:
			if sal[j][0] in alr:
				isnew = False
			else:
				isnew = True
				high.append(sal[j][0])
				lowsup[i].append(len(high) - 1)
				lowsup[sal[j][1]].append(len(high) - 1)
				highsub.append(i)
		elif isnew:
			lowsup[sal[j][1]].append(len(high) - 1)
print(n + len(high))
print(*low + high)
print(n + high.index(max(high)) + 1)
for i in range(n):
	ans = 0
	sal = max(high) + 1
	for x in lowsup[i]:
		if high[x] < sal:
			sal = high[x]
			ans = x + n + 1
	print(i + 1, ans)
for i in range(len(high)):
	ans = 0
	sal = max(high) + 1
	for x in lowsup[highsub[i]]:
		if high[x] > high[i] and high[x] < sal:
			sal = high[x]
			ans = x + n + 1
	if ans:
		print(i + n + 1, ans)


import math
import random
import heapq, bisect
import sys
from collections import deque, defaultdict
from fractions import Fraction
import sys
from collections import defaultdict
mod = 10 ** 9 + 7
mod1 = 998244353
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')

class TreeNode:

	def __init__(self, k, v):
		self.key = k
		self.value = v
		self.left = None
		self.right = None
		self.parent = None
		self.height = 1
		self.num_left = 1
		self.num_total = 1

class AvlTree:

	def __init__(self):
		self._tree = None

	def add(self, k, v):
		if not self._tree:
			self._tree = TreeNode(k, v)
			return
		node = self._add(k, v)
		if node:
			self._rebalance(node)

	def _add(self, k, v):
		node = self._tree
		while node:
			if k < node.key:
				if node.left:
					node = node.left
				else:
					node.left = TreeNode(k, v)
					node.left.parent = node
					return node.left
			elif node.key < k:
				if node.right:
					node = node.right
				else:
					node.right = TreeNode(k, v)
					node.right.parent = node
					return node.right
			else:
				node.value = v
				return

	@staticmethod
	def get_height(x):
		return x.height if x else 0

	@staticmethod
	def get_num_total(x):
		return x.num_total if x else 0

	def _rebalance(self, node):
		n = node
		while n:
			lh = self.get_height(n.left)
			rh = self.get_height(n.right)
			n.height = max(lh, rh) + 1
			balance_factor = lh - rh
			n.num_total = 1 + self.get_num_total(n.left) + self.get_num_total(n.right)
			n.num_left = 1 + self.get_num_total(n.left)
			if balance_factor > 1:
				if self.get_height(n.left.left) < self.get_height(n.left.right):
					self._rotate_left(n.left)
				self._rotate_right(n)
			elif balance_factor < -1:
				if self.get_height(n.right.right) < self.get_height(n.right.left):
					self._rotate_right(n.right)
				self._rotate_left(n)
			else:
				n = n.parent

	def _remove_one(self, node):
		replacement = node.left or node.right
		if node.parent:
			if AvlTree._is_left(node):
				node.parent.left = replacement
			else:
				node.parent.right = replacement
			replacement.parent = node.parent
			node.parent = None
		else:
			self._tree = replacement
			replacement.parent = None
		node.left = None
		node.right = None
		node.parent = None
		self._rebalance(replacement)

	def _remove_leaf(self, node):
		if node.parent:
			if AvlTree._is_left(node):
				node.parent.left = None
			else:
				node.parent.right = None
			self._rebalance(node.parent)
		else:
			self._tree = None
		node.parent = None
		node.left = None
		node.right = None

	def remove(self, k):
		node = self._get_node(k)
		if not node:
			return
		if AvlTree._is_leaf(node):
			self._remove_leaf(node)
			return
		if node.left and node.right:
			nxt = AvlTree._get_next(node)
			node.key = nxt.key
			node.value = nxt.value
			if self._is_leaf(nxt):
				self._remove_leaf(nxt)
			else:
				self._remove_one(nxt)
			self._rebalance(node)
		else:
			self._remove_one(node)

	def get(self, k):
		node = self._get_node(k)
		return node.value if node else -1

	def _get_node(self, k):
		if not self._tree:
			return None
		node = self._tree
		while node:
			if k < node.key:
				node = node.left
			elif node.key < k:
				node = node.right
			else:
				return node
		return None

	def get_at(self, pos):
		x = pos + 1
		node = self._tree
		while node:
			if x < node.num_left:
				node = node.left
			elif node.num_left < x:
				x -= node.num_left
				node = node.right
			else:
				return (node.key, node.value)
		raise IndexError('Out of ranges')

	@staticmethod
	def _is_left(node):
		return node.parent.left and node.parent.left == node

	@staticmethod
	def _is_leaf(node):
		return node.left is None and node.right is None

	def _rotate_right(self, node):
		if not node.parent:
			self._tree = node.left
			node.left.parent = None
		elif AvlTree._is_left(node):
			node.parent.left = node.left
			node.left.parent = node.parent
		else:
			node.parent.right = node.left
			node.left.parent = node.parent
		bk = node.left.right
		node.left.right = node
		node.parent = node.left
		node.left = bk
		if bk:
			bk.parent = node
		node.height = max(self.get_height(node.left), self.get_height(node.right)) + 1
		node.num_total = 1 + self.get_num_total(node.left) + self.get_num_total(node.right)
		node.num_left = 1 + self.get_num_total(node.left)

	def _rotate_left(self, node):
		if not node.parent:
			self._tree = node.right
			node.right.parent = None
		elif AvlTree._is_left(node):
			node.parent.left = node.right
			node.right.parent = node.parent
		else:
			node.parent.right = node.right
			node.right.parent = node.parent
		bk = node.right.left
		node.right.left = node
		node.parent = node.right
		node.right = bk
		if bk:
			bk.parent = node
		node.height = max(self.get_height(node.left), self.get_height(node.right)) + 1
		node.num_total = 1 + self.get_num_total(node.left) + self.get_num_total(node.right)
		node.num_left = 1 + self.get_num_total(node.left)

	@staticmethod
	def _get_next(node):
		if not node.right:
			return node.parent
		n = node.right
		while n.left:
			n = n.left
		return n

class SegmentTree1:

	def __init__(self, data, default=300006, func=lambda a, b: min(a, b)):
		self._default = default
		self._func = func
		self._len = len(data)
		self._size = _size = 1 << (self._len - 1).bit_length()
		self.data = [default] * (2 * _size)
		self.data[_size:_size + self._len] = data
		for i in reversed(range(_size)):
			self.data[i] = func(self.data[i + i], self.data[i + i + 1])

	def __delitem__(self, idx):
		self[idx] = self._default

	def __getitem__(self, idx):
		return self.data[idx + self._size]

	def __setitem__(self, idx, value):
		idx += self._size
		self.data[idx] = value
		idx >>= 1
		while idx:
			self.data[idx] = self._func(self.data[2 * idx], self.data[2 * idx + 1])
			idx >>= 1

	def __len__(self):
		return self._len

	def query(self, start, stop):
		if start == stop:
			return self.__getitem__(start)
		stop += 1
		start += self._size
		stop += self._size
		res = self._default
		while start < stop:
			if start & 1:
				res = self._func(res, self.data[start])
				start += 1
			if stop & 1:
				stop -= 1
				res = self._func(res, self.data[stop])
			start >>= 1
			stop >>= 1
		return res

	def __repr__(self):
		return 'SegmentTree({0})'.format(self.data)

class SegmentTree:

	def __init__(self, data, default=0, func=lambda a, b: a + b):
		self._default = default
		self._func = func
		self._len = len(data)
		self._size = _size = 1 << (self._len - 1).bit_length()
		self.data = [default] * (2 * _size)
		self.data[_size:_size + self._len] = data
		for i in reversed(range(_size)):
			self.data[i] = func(self.data[i + i], self.data[i + i + 1])

	def __delitem__(self, idx):
		self[idx] = self._default

	def __getitem__(self, idx):
		return self.data[idx + self._size]

	def __setitem__(self, idx, value):
		idx += self._size
		self.data[idx] = value
		idx >>= 1
		while idx:
			self.data[idx] = self._func(self.data[2 * idx], self.data[2 * idx + 1])
			idx >>= 1

	def __len__(self):
		return self._len

	def query(self, start, stop):
		if start == stop:
			return self.__getitem__(start)
		stop += 1
		start += self._size
		stop += self._size
		res = self._default
		while start < stop:
			if start & 1:
				res = self._func(res, self.data[start])
				start += 1
			if stop & 1:
				stop -= 1
				res = self._func(res, self.data[stop])
			start >>= 1
			stop >>= 1
		return res

	def __repr__(self):
		return 'SegmentTree({0})'.format(self.data)

class Factorial:

	def __init__(self, MOD):
		self.MOD = MOD
		self.factorials = [1, 1]
		self.invModulos = [0, 1]
		self.invFactorial_ = [1, 1]

	def calc(self, n):
		if n <= -1:
			print('Invalid argument to calculate n!')
			print('n must be non-negative value. But the argument was ' + str(n))
			exit()
		if n < len(self.factorials):
			return self.factorials[n]
		nextArr = [0] * (n + 1 - len(self.factorials))
		initialI = len(self.factorials)
		prev = self.factorials[-1]
		m = self.MOD
		for i in range(initialI, n + 1):
			prev = nextArr[i - initialI] = prev * i % m
		self.factorials += nextArr
		return self.factorials[n]

	def inv(self, n):
		if n <= -1:
			print('Invalid argument to calculate n^(-1)')
			print('n must be non-negative value. But the argument was ' + str(n))
			exit()
		p = self.MOD
		pi = n % p
		if pi < len(self.invModulos):
			return self.invModulos[pi]
		nextArr = [0] * (n + 1 - len(self.invModulos))
		initialI = len(self.invModulos)
		for i in range(initialI, min(p, n + 1)):
			next = -self.invModulos[p % i] * (p // i) % p
			self.invModulos.append(next)
		return self.invModulos[pi]

	def invFactorial(self, n):
		if n <= -1:
			print('Invalid argument to calculate (n^(-1))!')
			print('n must be non-negative value. But the argument was ' + str(n))
			exit()
		if n < len(self.invFactorial_):
			return self.invFactorial_[n]
		self.inv(n)
		nextArr = [0] * (n + 1 - len(self.invFactorial_))
		initialI = len(self.invFactorial_)
		prev = self.invFactorial_[-1]
		p = self.MOD
		for i in range(initialI, n + 1):
			prev = nextArr[i - initialI] = prev * self.invModulos[i % p] % p
		self.invFactorial_ += nextArr
		return self.invFactorial_[n]

class Combination:

	def __init__(self, MOD):
		self.MOD = MOD
		self.factorial = Factorial(MOD)

	def ncr(self, n, k):
		if k < 0 or n < k:
			return 0
		k = min(k, n - k)
		f = self.factorial
		return f.calc(n) * f.invFactorial(max(n - k, k)) * f.invFactorial(min(k, n - k)) % self.MOD

def powm(a, n, m):
	if a == 1 or n == 0:
		return 1
	if n % 2 == 0:
		s = powm(a, n // 2, m)
		return s * s % m
	else:
		return a * powm(a, n - 1, m) % m

def sort_list(list1, list2):
	zipped_pairs = zip(list2, list1)
	z = [x for (_, x) in sorted(zipped_pairs)]
	return z

def product(l):
	por = 1
	for i in range(len(l)):
		por *= l[i]
	return por

def binarySearchCount(arr, n, key):
	left = 0
	right = n - 1
	count = 0
	while left <= right:
		mid = int((right + left) / 2)
		if arr[mid] < key:
			count = mid + 1
			left = mid + 1
		else:
			right = mid - 1
	return count

def countdig(n):
	c = 0
	while n > 0:
		n //= 10
		c += 1
	return c

def binary(x, length):
	y = bin(x)[2:]
	return y if len(y) >= length else '0' * (length - len(y)) + y

def countGreater(arr, n, k):
	l = 0
	r = n - 1
	leftGreater = n
	while l <= r:
		m = int(l + (r - l) / 2)
		if arr[m] > k:
			leftGreater = m
			r = m - 1
		else:
			l = m + 1
	return n - leftGreater

class TrieNode:

	def __init__(self):
		self.children = [None] * 26
		self.isEndOfWord = False

class Trie:

	def __init__(self):
		self.root = self.getNode()

	def getNode(self):
		return TrieNode()

	def _charToIndex(self, ch):
		return ord(ch) - ord('a')

	def insert(self, key):
		pCrawl = self.root
		length = len(key)
		for level in range(length):
			index = self._charToIndex(key[level])
			if not pCrawl.children[index]:
				pCrawl.children[index] = self.getNode()
			pCrawl = pCrawl.children[index]
		pCrawl.isEndOfWord = True

	def search(self, key):
		pCrawl = self.root
		length = len(key)
		for level in range(length):
			index = self._charToIndex(key[level])
			if not pCrawl.children[index]:
				return False
			pCrawl = pCrawl.children[index]
		return pCrawl != None and pCrawl.isEndOfWord

class Node:

	def __init__(self, data):
		self.data = data
		self.count = 0
		self.left = None
		self.right = None

class BinaryTrie:

	def __init__(self):
		self.root = Node(0)

	def insert(self, pre_xor):
		self.temp = self.root
		for i in range(31, -1, -1):
			val = pre_xor & 1 << i
			if val:
				if not self.temp.right:
					self.temp.right = Node(0)
				self.temp = self.temp.right
				self.temp.count += 1
			if not val:
				if not self.temp.left:
					self.temp.left = Node(0)
				self.temp = self.temp.left
				self.temp.count += 1
		self.temp.data = pre_xor

	def query(self, xor):
		self.temp = self.root
		for i in range(31, -1, -1):
			val = xor & 1 << i
			if not val:
				if self.temp.left and self.temp.left.count > 0:
					self.temp = self.temp.left
				elif self.temp.right:
					self.temp = self.temp.right
			elif self.temp.right and self.temp.right.count > 0:
				self.temp = self.temp.right
			elif self.temp.left:
				self.temp = self.temp.left
			self.temp.count -= 1
		return xor ^ self.temp.data
n = int(input())
p = [i for i in range(4 * n + 1)]
graph = defaultdict(set)

def get(a):
	if p[a] != a:
		p[a] = get(p[a])
	return p[a]

def union(a, b):
	a = get(a)
	b = get(b)
	p[a] = b
a = []
k = n
for i in range(n):
	a.append(list(map(int, input().split())))
ans = [0] * (4 * n + 1)
we = []
for i in range(n):
	ans[i] = a[i][i]
	for j in range(i + 1, n):
		we.append((a[i][j], i, j))
we.sort()
last = defaultdict(int)
u = defaultdict(int)
for jq in range(len(we)):
	t = k
	i = we[jq][1]
	j = we[jq][2]
	if get(j) == get(i):
		continue
	if we[jq][0] == last[get(i)]:
		k = u[get(i)]
		t -= 1
	ans[k] = we[jq][0]
	graph[k].add(get(j))
	graph[k].add(get(i))
	union(get(i), k)
	union(get(j), k)
	last[get(i)] = we[jq][0]
	u[get(i)] = k
	k = t + 1
print(k)
print(*ans[:k])
print(k)
for i in range(k):
	for j in graph[i]:
		if i == j:
			continue
		print(j + 1, i + 1)


import bisect
nodes = []

class Node:

	def __init__(self, idx, salary):
		self.idx = idx
		self.salary = salary
		self.children = []
		nodes.append(self)

def find_parent(board, parent_node, row, y):
	for child in parent_node.children:
		if board[child.idx][y] == parent_node.salary:
			continue
		else:
			return find_parent(board, child, row, y)
	return parent_node

def main():
	n = int(input())
	board = []
	for i in range(n):
		a = list(map(int, input().split()))
		board.append(a)
	tree = {}
	idx = 0
	row = sorted(board[idx])
	prev = None
	for i in range(n):
		salary = row[i]
		if prev and prev.salary == salary:
			continue
		node = Node(idx, salary)
		if prev:
			node.children.append(prev)
		prev = node
		tree[salary] = node
	for i in range(1, n):
		intersect = board[i][0]
		row = sorted(board[i])
		pos = bisect.bisect_left(row, intersect)
		prev = find_parent(board, tree[intersect], row, i)
		for j in range(pos - 1, -1, -1):
			if row[j] >= prev.salary:
				continue
			node = Node(i, row[j])
			prev.children.append(node)
			prev = node
	print(len(nodes))
	nodes.sort(key=lambda x: len(x.children))
	Mx = 0
	sals = []
	for i in range(len(nodes)):
		sals.append(nodes[i].salary)
		if nodes[Mx].salary < nodes[i].salary:
			Mx = i
		nodes[i].index = i
	print(*sals)
	print(Mx + 1)
	to_do = [Mx]
	z = 0
	while z < len(to_do):
		current = to_do[z]
		z += 1
		for child in nodes[current].children:
			print(child.index + 1, nodes[current].index + 1)
			to_do.append(child.index)
main()


import heapq

class UF:

	def __init__(self, N):
		self.par = list(range(N))
		self.sz = [1] * N

	def find(self, x):
		if self.par[x] != x:
			self.par[x] = self.find(self.par[x])
		return self.par[x]

	def union(self, x, y):
		(xr, yr) = (self.find(x), self.find(y))
		if xr == yr:
			return False
		if self.sz[xr] < self.sz[yr]:
			(xr, yr) = (yr, xr)
		self.par[yr] = xr
		self.sz[xr] += self.sz[yr]
		return True

	def size(self, x):
		return self.sz[self.find(x)]

	def connected(self, x, y):
		return self.find(x) == self.find(y)

def main():
	n = int(input())
	uf = UF(n * n + 1)
	heap = []
	ans_list = []
	edges = []
	parent_map = {i: i for i in range(n ** 2 + 1)}
	for i in range(n):
		cur_lst = list(map(int, input().split(' ')))
		for j in range(i, n):
			if i == j:
				ans_list.append(cur_lst[j])
			else:
				heapq.heappush(heap, (cur_lst[j], i, j))
	while heap:
		(cur_anc_salary, low1, low2) = heapq.heappop(heap)
		(c1, c2) = (parent_map[uf.find(low1)], parent_map[uf.find(low2)])
		if c1 == c2:
			continue
		if ans_list[c1] == cur_anc_salary:
			edges.append((c2, c1))
			uf.union(c1, c2)
			parent_map[uf.find(c1)] = c1
		elif ans_list[c2] == cur_anc_salary:
			edges.append((c1, c2))
			uf.union(c1, c2)
			parent_map[uf.find(c1)] = c2
		else:
			new_node = len(ans_list)
			ans_list.append(cur_anc_salary)
			uf.union(c1, c2)
			uf.union(c1, new_node)
			edges.append((c1, new_node))
			edges.append((c2, new_node))
			parent_map[uf.find(new_node)] = new_node
	print(len(ans_list))
	print(' '.join(map(str, ans_list)))
	print(len(ans_list))
	for (x, y) in edges:
		print('{} {}'.format(x + 1, y + 1))
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')
main()


import sys
input = sys.stdin.readline

class DSU:

	def __init__(self, n):
		self.uf = {i: i for i in range(n)}

	def find(self, x):
		self.uf.setdefault(x, x)
		if self.uf[x] != x:
			self.uf[x] = self.find(self.uf[x])
		return self.uf[x]

	def union(self, x, y):
		(px, py) = (self.find(x), self.find(y))
		self.uf[px] = py
k = int(input())
A = [list(map(int, input().split())) for _ in range(k)]
B = [A[i][i] for i in range(k)]
C = sorted(((A[i][j], i + 1, j + 1) for i in range(k) for j in range(i + 1, k)))
ans = []
dsu = DSU(k)
for (c, i, j) in C:
	(pi, pj) = (dsu.find(i), dsu.find(j))
	if pi == pj:
		continue
	if c > B[pi - 1] and c > B[pj - 1]:
		B.append(c)
		ans.append((pi, len(B)))
		ans.append((pj, len(B)))
		dsu.union(pi, len(B))
		dsu.union(pj, len(B))
	elif c == B[pi - 1]:
		ans.append((pj, pi))
		dsu.union(pj, pi)
	else:
		ans.append((pi, pj))
		dsu.union(pi, pj)
print(len(B))
print(*B)
print(dsu.find(1))
for a in ans:
	print(*a)


from sys import stdin, stdout

def dogeforces(c_a, a_a):
	global n
	l_a = [i for i in range(n)]
	return dfs(c_a, a_a, l_a)

def dfs(c_a, a_a, l_a):
	global n
	global d_a
	if len(l_a) == 1:
		return l_a[0]
	root = -1
	for l in l_a:
		root = max(root, a_a[l_a[0]][l])
	gp_a = []
	for l in l_a:
		gp = -1
		for j in range(len(gp_a)):
			g = gp_a[j][0]
			if a_a[l][g] != root:
				gp = j
				break
		if gp == -1:
			gp = len(gp_a)
			gp_a.append([])
		gp_a[gp].append(l)
	v = n
	c_a.append(root)
	n += 1
	for gp in gp_a:
		sr = dfs(c_a, a_a, gp)
		d_a.append([sr, v])
	return v
n = int(stdin.readline())
a_a = []
c_a = []
for i in range(n):
	a_a.append(list(map(int, stdin.readline().split())))
	c_a.append(a_a[i][i])
d_a = []
root = dogeforces(c_a, a_a)
stdout.write(str(n) + '\n')
stdout.write(' '.join(map(str, c_a)) + '\n')
stdout.write(str(root + 1) + '\n')
for d in d_a:
	stdout.write(str(d[0] + 1) + ' ' + str(d[1] + 1) + '\n')


class node:

	def __init__(self, id_no, val):
		self.id_no = id_no
		self.val = val
		self.child = []
import sys, functools, collections, bisect, math, heapq
input = sys.stdin.readline

def dfs(root, pre):
	values.append((root.id_no, root.val, pre))
	for child in root.child:
		dfs(child, root.id_no)

def construct(a):
	global x
	if len(a) == 1:
		return node(a[0] + 1, arr[a[0]][a[0]])
	curr = 0
	ch = collections.defaultdict(list)
	for i in range(len(a)):
		for j in range(i + 1, len(a)):
			if arr[a[i]][a[j]] >= curr:
				curr = arr[a[i]][a[j]]
	for i in a:
		for j in range(len(ch) + 1):
			for k in ch[j]:
				if arr[k][i] == curr:
					break
			else:
				ch[j].append(i)
				break
	root = node(x, curr)
	x += 1
	for i in ch:
		root.child.append(construct(ch[i]))
	return root
n = int(input())
x = n + 1
a = list(range(n))
arr = []
for i in range(n):
	arr.append(list(map(int, input().strip().split())))
root = construct(a)
values = []
dfs(root, -1)
N = len(values)
v = [0] * N
parent = []
for i in values:
	v[i[0] - 1] = i[1]
	if i[2] != -1:
		parent.append(str(i[0]) + ' ' + str(i[2]))
print(len(v))
print(' '.join((str(i) for i in v)))
print(root.id_no)
print('\n'.join(parent))


def f(s):
	global num, sal, super
	rootnum = num
	num += 1
	groups = []
	rootsal = 0
	while len(s) > 0:
		x = s.pop()
		if rootsal == 0:
			rootsal = max([a[x][i] for i in s])
			sal[rootnum] = rootsal
		sib = set([i for i in s if a[x][i] != rootsal])
		sib.add(x)
		rest = s.difference(sib)
		if len(sib) == 1:
			super[x + 1] = rootnum
		else:
			groups += [sib]
		s = rest
	for s in groups:
		managernum = f(s)
		super[managernum] = rootnum
	return rootnum
n = int(input())
a = [[int(x) for x in input().split()] for _ in range(n)]
sal = {x + 1: a[x][x] for x in range(n)}
super = {}
num = n + 1
head = f(set(range(n)))
print(num - 1)
print(' '.join([str(x) for x in sal.values()]))
print(head)
[print(f'{x} {super[x]}') for x in super]


from sys import stdin, stdout
import heapq
from collections import defaultdict
import math

def main():
	N = int(stdin.readline())
	arr = []
	for _ in range(N):
		arr.append(list(map(int, stdin.readline().split())))
	salary = [-1 for _ in range(N)]
	head = -1
	connect = []
	jumper = defaultdict(dict)
	n = N
	for i in range(N):
		salary[i] = arr[i][i]
		(min_left, left_pos) = (5001, -1)
		rights = set()
		for j in range(N):
			if i == j:
				continue
			if j < i:
				if min_left > arr[i][j]:
					min_left = arr[i][j]
					left_pos = j
				continue
			if arr[i][j] < min_left:
				rights.add(arr[i][j])
		if rights:
			rights = list(rights)
			rights.sort(reverse=True)
			for (k, x) in enumerate(rights):
				n += 1
				salary.append(x)
				if k == 0:
					if i == 0:
						head = n
						jumper[i][x] = n
					else:
						connect.append((n, jumper[left_pos][min_left]))
						jumper[i][x] = n
					continue
				connect.append((n, n - 1))
				jumper[i][x] = n
			connect.append((i + 1, n))
		else:
			connect.append((i + 1, jumper[left_pos][min_left]))
	stdout.write(str(n) + '\n')
	stdout.write(' '.join([str(x) for x in salary]) + '\n')
	stdout.write(str(head) + '\n')
	for (a, b) in connect:
		stdout.write(str(a) + ' ' + str(b) + '\n')
main()


import sys
import bisect as bi
import collections as cc
input = sys.stdin.readline
I = lambda : list(map(int, input().split()))

def find(a):
	while par[a] != a:
		a = par[a]
	return a

def join(a, b):
	x = find(a)
	y = find(b)
	if x != y:
		par[x] = par[y] = max(x, y)
for tc in range(1):
	(n,) = I()
	par = list(range(6000))
	ans = [None for i in range(10 ** 4)]
	ar = []
	for i in range(n):
		temp = I()
		for j in range(n):
			if i == j:
				ans[i] = temp[j]
			elif i < j:
				ar.append([temp[j], i, j])
	ar.sort()
	edges = []
	new_edge = n
	for i in range(len(ar)):
		now = ar[i]
		a = find(now[1])
		b = find(now[2])
		if a == b:
			continue
		elif max(ans[a], ans[b]) == now[0]:
			if ans[a] > ans[b]:
				par[b] = a
				edges.append([b, a])
			else:
				par[a] = b
				edges.append([a, b])
			continue
		else:
			ans[new_edge] = now[0]
			edges.append([a, new_edge])
			edges.append([b, new_edge])
			par[a] = new_edge
			par[b] = new_edge
			new_edge += 1
	print(new_edge)
	for i in range(new_edge):
		print(ans[i], end=' ')
	print()
	print(find(0) + 1)
	for (x, y) in edges:
		print(x + 1, y + 1)


n = int(input())
a = [list(map(int, input().split())) for i in range(n)]
val = [-1] * 10 ** 6
par = [-1] * 10 ** 6
for i in range(n):
	val[i] = a[i][i]
edgetank = []
for i in range(n):
	for j in range(i + 1, n):
		edgetank.append((a[i][j], i, j))
edgetank.sort()

def findroot(x):
	now = x
	while par[now] >= 0:
		now = par[now]
	return now
newvertex = n
for (w, u, v) in edgetank:
	u_root = findroot(u)
	v_root = findroot(v)
	if u_root == v_root:
		continue
	if val[u_root] == w:
		par[v_root] = u_root
	elif val[v_root] == w:
		par[u_root] = v_root
	else:
		par[u_root] = newvertex
		par[v_root] = newvertex
		val[newvertex] = w
		newvertex += 1
print(newvertex)
print(*val[:newvertex])
emp_sup = []
for i in range(newvertex):
	if par[i] != -1:
		emp_sup.append('{} {}'.format(i + 1, par[i] + 1))
print(newvertex)
print(*emp_sup, sep='\n')


import sys
from sys import stdin
from collections import deque
tt = 1
for loop in range(tt):
	n = int(stdin.readline())
	a = [list(map(int, stdin.readline().split())) for i in range(n)]
	c = [a[i][i] for i in range(n)]
	vlis = []
	q = deque([[i for i in range(n)] + [None]])
	while q:
		lis = q.popleft()
		oldp = lis[-1]
		del lis[-1]
		if len(lis) == 1:
			vlis.append((lis[0] + 1, oldp + 1))
			continue
		nmax = 0
		for i in range(len(lis)):
			for j in range(i):
				nmax = max(nmax, a[lis[i]][lis[j]])
		group = [[lis[0]]]
		for i in range(1, len(lis)):
			nv = lis[i]
			for ng in group:
				if a[ng[0]][nv] != nmax:
					ng.append(nv)
					break
			else:
				group.append([nv])
		newp = len(c)
		if oldp != None:
			vlis.append((newp + 1, oldp + 1))
		c.append(nmax)
		for ng in group:
			ng.append(newp)
			q.append(ng)
	print(len(c))
	print(*c)
	print(n + 1)
	for (v, u) in vlis:
		print(v, u)


import sys
input = sys.stdin.readline
from operator import itemgetter
n = int(input())
SA = [list(map(int, input().split())) for i in range(n)]
C = [-1]
for i in range(n):
	C.append(SA[i][i])
SAS = []
for i in range(n):
	for j in range(i + 1, n):
		SAS.append((SA[i][j], i + 1, j + 1))
SAS.sort(key=itemgetter(0))
P = [i for i in range(10 ** 5)]
ANS = []

def nowroot(i):
	while P[i] != i:
		i = P[i]
	return i
ANS = [-1] * 10 ** 5
for tt in range(len(SAS)):
	(x, i, j) = SAS[tt]
	i = nowroot(i)
	j = nowroot(j)
	if SAS[tt][0] == C[i] or SAS[tt][0] == C[j]:
		if SAS[tt][0] == C[i]:
			L = i
		else:
			L = j
		if i != L:
			ANS[i] = L
		if j != L:
			ANS[j] = L
		P[i] = L
		P[j] = L
	else:
		C.append(x)
		L = len(C) - 1
		if i != L:
			ANS[i] = L
		if j != L:
			ANS[j] = L
		P[i] = L
		P[j] = L
print(len(C) - 1)
print(*C[1:])
print(len(C) - 1)
for i in range(1, len(C) - 1):
	print(i, ANS[i])


import sys
input = sys.stdin.readline
n = int(input())
a = [list(map(int, input().split())) for _ in range(n)]
e = [[] for _ in range(n)]

def solve(t):
	global e
	ind = []
	x = 1
	for i in range(n):
		if t & x:
			ind.append(i)
		x <<= 1
	mx = 0
	mn = 5000
	for i in ind:
		for j in ind:
			mx = max(mx, a[i][j])
			mn = min(mn, a[i][j])
	if len(ind) == 1:
		return ind[0]
	e.append([])
	if mn == mx:
		for i in ind:
			e[-1].append(i)
		return len(e) - 1
	z = len(e) - 1
	vis = [0] * n
	for i in ind:
		if vis[i]:
			continue
		tt = 0
		for j in ind:
			if vis[j]:
				continue
			if a[i][j] != mx:
				tt |= 1 << j
				vis[j] = 1
		e[z].append(solve(tt))
	return z
solve((1 << n) - 1)
s = [n]
vis = [0] * len(e)
vis[n] = 1
order = []
parent = [-1] * len(e)
while len(s):
	x = s.pop()
	order.append(x)
	for y in e[x]:
		if vis[y]:
			continue
		vis[y] = 1
		s.append(y)
		parent[y] = x
import heapq
hpush = heapq.heappush
hpop = heapq.heappop
h = [[] for _ in range(len(e))]
for i in range(n):
	for x in a[i]:
		hpush(h[i], x)
res = [0] * len(e)
order.reverse()
for y in order:
	res[y] = hpop(h[y])
	if parent[y] == -1:
		continue
	x = parent[y]
	if len(h[x]) == 0:
		while len(h[y]):
			v = hpop(h[y])
			if v > res[y]:
				hpush(h[x], v)
	else:
		while len(h[x]) and h[x][0] <= res[y]:
			hpop(h[x])
print(len(e))
print(*res)
print(n + 1)
for x in range(len(e)):
	for y in e[x]:
		print(y + 1, x + 1)


class UnionFind:

	def __init__(self, n):
		self.n = n
		self.parents = [-1] * n

	def find(self, x):
		if self.parents[x] < 0:
			return x
		else:
			self.parents[x] = self.find(self.parents[x])
			return self.parents[x]

	def union(self, x, y):
		x = self.find(x)
		y = self.find(y)
		if x == y:
			return
		if self.parents[x] > self.parents[y]:
			(x, y) = (y, x)
		self.parents[x] += self.parents[y]
		self.parents[y] = x

	def size(self, x):
		return -self.parents[self.find(x)]

	def same(self, x, y):
		return self.find(x) == self.find(y)

	def members(self, x):
		root = self.find(x)
		return [i for i in range(self.n) if self.find(i) == root]

	def roots(self):
		return [i for (i, x) in enumerate(self.parents) if x < 0]

	def group_count(self):
		return len(self.roots())

	def all_group_members(self):
		groups = {r: [] for r in self.roots()}
		for i in range(self.N):
			groups[self.find(i)].append(i)
		return groups

	def __str__(self):
		return '\n'.join(('{}: {}'.format(r, self.members(r)) for r in self.roots()))

def popcount(x):
	return bin(x).count('1')

def compress(arr):
	com = {e: i for (i, e) in enumerate(sorted(set(arr)))}
	rcom = list(com.keys())
	return (com, rcom)
import os, io
input = io.BytesIO(os.read(0, os.fstat(0).st_size)).readline
n = int(input())
uf = UnionFind(n * n)
grid = []
ans = []
edges = []
for i in range(n):
	a = list(map(int, input().split()))
	grid.append(a)
relations = []
for i in range(n):
	for j in range(i, n):
		if i == j:
			ans.append(grid[i][j])
			continue
		relations.append((i, j, grid[i][j]))
relations.sort(key=lambda thing: thing[2])
rootfinder = [0] * (500 * 500)
for i in range(n):
	rootfinder[i] = i
k = n
for p in range(len(relations)):
	(i, j, value) = relations[p]
	if uf.same(i, j):
		continue
	a = uf.find(i)
	b = uf.find(j)
	l = rootfinder[a]
	m = rootfinder[b]
	if ans[l] == value:
		edges.append([m + 1, l + 1])
		uf.union(a, b)
		newroot = uf.find(a)
		rootfinder[newroot] = l
	elif ans[m] == value:
		edges.append([l + 1, m + 1])
		uf.union(a, b)
		newroot = uf.find(a)
		rootfinder[newroot] = m
	else:
		ans.append(value)
		uf.union(a, b)
		newroot = uf.find(a)
		rootfinder[newroot] = k
		edges.append([m + 1, k + 1])
		edges.append([l + 1, k + 1])
		k += 1
print(k)
print(' '.join(map(str, ans)))
print(rootfinder[uf.find(0)] + 1)
for edge in edges:
	print(' '.join(map(str, edge)))


class UnionFind:

	def __init__(self, n):
		self.n = n
		self.parents = [-1] * n

	def find(self, x):
		if self.parents[x] < 0:
			return x
		else:
			self.parents[x] = self.find(self.parents[x])
			return self.parents[x]

	def union(self, x, y):
		x = self.find(x)
		y = self.find(y)
		if x == y:
			return
		if self.parents[x] > self.parents[y]:
			(x, y) = (y, x)
		self.parents[x] += self.parents[y]
		self.parents[y] = x

	def size(self, x):
		return -self.parents[self.find(x)]

	def same(self, x, y):
		return self.find(x) == self.find(y)
n = int(input())
uf = UnionFind(n * n)
grid = []
ans = []
edges = []
for i in range(n):
	a = list(map(int, input().split()))
	grid.append(a)
relations = []
for i in range(n):
	for j in range(i, n):
		if i == j:
			ans.append(grid[i][j])
			continue
		relations.append((i, j, grid[i][j]))
relations.sort(key=lambda thing: thing[2])
rootfinder = [0] * (500 * 500)
for i in range(n):
	rootfinder[i] = i
k = n
for p in range(len(relations)):
	(i, j, value) = relations[p]
	if uf.same(i, j):
		continue
	a = uf.find(i)
	b = uf.find(j)
	l = rootfinder[a]
	m = rootfinder[b]
	if ans[l] == value:
		edges.append([m + 1, l + 1])
		uf.union(a, b)
		newroot = uf.find(a)
		rootfinder[newroot] = l
	elif ans[m] == value:
		edges.append([l + 1, m + 1])
		uf.union(a, b)
		newroot = uf.find(a)
		rootfinder[newroot] = m
	else:
		ans.append(value)
		uf.union(a, b)
		newroot = uf.find(a)
		rootfinder[newroot] = k
		edges.append([m + 1, k + 1])
		edges.append([l + 1, k + 1])
		k += 1
print(k)
print(*ans)
print(rootfinder[uf.find(0)] + 1)
for edge in edges:
	print(*edge)


import sys
sys.setrecursionlimit(10 ** 5)
int1 = lambda x: int(x) - 1
p2D = lambda x: print(*x, sep='\n')

def II():
	return int(sys.stdin.buffer.readline())

def MI():
	return map(int, sys.stdin.buffer.readline().split())

def LI():
	return list(map(int, sys.stdin.buffer.readline().split()))

def LLI(rows_number):
	return [LI() for _ in range(rows_number)]

def BI():
	return sys.stdin.buffer.readline().rstrip()

def SI():
	return sys.stdin.buffer.readline().rstrip().decode()
inf = 10 ** 16
md = 10 ** 9 + 7

class UnionFind:

	def __init__(self, n):
		self.state = [-1] * n
		self.size_table = [1] * n
		self.cnt = n

	def root(self, u):
		v = self.state[u]
		if v < 0:
			return u
		self.state[u] = res = self.root(v)
		return res

	def merge(self, u, v):
		ru = self.root(u)
		rv = self.root(v)
		if ru == rv:
			return
		du = self.state[ru]
		dv = self.state[rv]
		if du > dv:
			(ru, rv) = (rv, ru)
		if du == dv:
			self.state[ru] -= 1
		self.state[rv] = ru
		self.cnt -= 1
		self.size_table[ru] += self.size_table[rv]
		return

	def size(self, u):
		return self.size_table[self.root(u)]
from collections import defaultdict
n = II()
aa = LLI(n)
ss = []
for u in range(n):
	ss.append(aa[u][u])
stou = defaultdict(list)
for u in range(n):
	for v in range(u):
		s = aa[u][v]
		stou[s].append((u, v))
uf = UnionFind(n)
node = n
boss = list(range(n))
edge = set()
for (s, uv) in sorted(stou.items()):
	uu = set()
	for (u, v) in uv:
		uf.merge(u, v)
		uu.add(u)
		uu.add(v)
	rtou = defaultdict(list)
	for u in uu:
		r = uf.root(u)
		rtou[r].append(u)
	for (r, vv) in rtou.items():
		for v in vv:
			edge.add((boss[v], node))
			boss[v] = node
		ss.append(s)
		node += 1
print(node)
print(*ss)
print(node)
for (u, v) in edge:
	print(u + 1, v + 1)


import io
import os
from collections import Counter, defaultdict, deque

def solve(N, A):
	parent = [-1] * N
	children = [[]] * N
	costs = [A[i][i] for i in range(N)]
	leafs = list(range(N))
	q = deque([(leafs, -1)])
	while q:
		(leafs, p) = q.pop()
		assert len(leafs) >= 2
		rootCost = 0
		for i in range(len(leafs)):
			for j in range(i + 1, len(leafs)):
				rootCost = max(rootCost, A[leafs[i]][leafs[j]])
		comps = [[leafs[0]]]
		for i in range(1, len(leafs)):
			x = leafs[i]
			for comp in comps:
				if A[comp[0]][x] != rootCost:
					comp.append(x)
					break
			else:
				comps.append([x])
		assert len(comps) > 1
		for c1 in comps[0]:
			for c2 in comps[1]:
				assert A[c1][c2] == rootCost
		newId = len(children)
		children.append([])
		parent.append(p)
		costs.append(rootCost)
		if p != -1:
			children[p].append(newId)
		for comp in comps:
			if len(comp) == 1:
				parent[comp[0]] = newId
				children[newId].append(comp[0])
			else:
				q.append((comp, newId))
	root = N
	K = len(parent)
	return str(K) + '\n' + ' '.join((str(c) for c in costs)) + '\n' + str(root + 1) + '\n' + '\n'.join((str(i + 1) + ' ' + str(parent[i] + 1) for i in range(K) if i != root))
input = io.BytesIO(os.read(0, os.fstat(0).st_size)).readline
TC = 1
for tc in range(1, TC + 1):
	(N,) = [int(x) for x in input().split()]
	A = [[int(x) for x in input().split()] for i in range(N)]
	ans = solve(N, A)
	print(ans)


import sys, math, itertools
from collections import Counter, deque, defaultdict
from bisect import bisect_left, bisect_right
from heapq import heappop, heappush, heapify, nlargest
from copy import deepcopy
mod = 10 ** 9 + 7
INF = float('inf')

def inp():
	return int(sys.stdin.readline())

def inpl():
	return list(map(int, sys.stdin.readline().split()))

def inpl_1():
	return list(map(lambda x: int(x) - 1, sys.stdin.readline().split()))

def inps():
	return sys.stdin.readline()

def inpsl(x):
	tmp = sys.stdin.readline()
	return list(tmp[:x])

def err(x):
	print(x)
	exit()

class UnionFind:

	def __init__(self, n):
		self.n = n
		self.parents = [-1] * n

	def find(self, x):
		if self.parents[x] < 0:
			return x
		else:
			self.parents[x] = self.find(self.parents[x])
			return self.parents[x]

	def union(self, x, y):
		x = self.find(x)
		y = self.find(y)
		if x == y:
			return
		if self.parents[x] > self.parents[y]:
			(x, y) = (y, x)
		self.parents[x] += self.parents[y]
		self.parents[y] = x

	def size(self, x):
		return -self.parents[self.find(x)]

	def same(self, x, y):
		return self.find(x) == self.find(y)

	def members(self, x):
		root = self.find(x)
		return [i for i in range(self.n) if self.find(i) == root]

	def roots(self):
		return [i for (i, x) in enumerate(self.parents) if x < 0]

	def group_count(self):
		return len(self.roots())

	def all_group_members(self):
		return {r: self.members(r) for r in self.roots()}
n = inp()
a = [inpl() for _ in range(n)]
lis = []
res = []
for i in range(n):
	for j in range(i, n):
		if i == j:
			res.append(a[i][j])
		else:
			lis.append((a[i][j], i, j))
lis.sort()
pa = [-1] * 2000
mostpa = [-1] * n
idx = n
nowsal = lis[0][0]
vers = []
uf = UnionFind(n)

def sol(nowsal, vers):
	global idx
	for (u, v) in vers:
		uf.union(u, v)
	pat = defaultdict(list)
	for (u, v) in vers:
		x = uf.find(u)
		pat[x].append(u)
		pat[x].append(v)
	for u in pat.values():
		for v in u:
			if pa[v] == -1:
				pa[v] = idx
			else:
				pa[mostpa[v]] = idx
			mostpa[v] = idx
		res.append(nowsal)
		idx += 1
for (sal, i, j) in lis:
	if sal != nowsal:
		sol(nowsal, vers)
		nowsal = sal
		vers = []
	vers.append((i, j))
sol(nowsal, vers)
ln = len(res)
print(ln)
print(*res)
print(ln)
for i in range(ln - 1):
	print(i + 1, pa[i] + 1)


import os, sys
from io import BytesIO, IOBase

def find(parent, x):
	if x == parent[x]:
		return x
	parent[x] = find(parent, parent[x])
	return parent[x]

def union(parent, a, b, edg):
	if a != b:
		edg.append((a + 1, b + 1))
		parent[a] = b

def main():
	n = int(input())
	a = [list(map(int, input().split())) for _ in range(n)]
	parent = [i for i in range(n)]
	sal = [a[i][i] for i in range(n)]
	rel = [(i, j, a[i][j]) for i in range(n) for j in range(i + 1, n)]
	rel.sort(key=lambda xx: xx[2])
	edg = []
	for i in rel:
		(a, b, c) = i
		(a, b) = (find(parent, a), find(parent, b))
		if sal[a] == c and sal[b] == c:
			continue
		elif sal[a] == c:
			union(parent, b, a, edg)
		elif sal[b] == c:
			union(parent, a, b, edg)
		else:
			parent.append(len(parent))
			sal.append(c)
			union(parent, a, len(parent) - 1, edg)
			union(parent, b, len(parent) - 1, edg)
	print(len(sal))
	print(*sal)
	print(len(sal))
	for i in edg:
		print(*i)
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')
main()


import sys
input = sys.stdin.readline
idx = 0
vis = None
a = None
e = None

def rec(c):
	global idx
	if len(c) == 1:
		z = c[0]
		vis[z] = -1
		cost[z] = a[z][z]
		return z
	idx += 1
	now = idx
	z = 0
	for i in c:
		vis[i] = -1
		for j in c:
			if i != j:
				z = max(z, a[i][j])
	cost[now] = z
	n = len(a)
	cc = 0
	w = []
	for i in c:
		if vis[i] < 0:
			q = [i]
			cc += 1
			vis[i] = cc
			qi = 0
			while qi < len(q):
				v = q[qi]
				qi += 1
				for j in c:
					if v != j and a[v][j] < z and (vis[j] < 0):
						q.append(j)
						vis[j] = cc
			w.append(q)
	for b in w:
		e.append((rec(b), now))
	return now

def solve():
	global idx, vis, a, e, cost
	n = int(input())
	a = [None] * n
	for i in range(n):
		a[i] = list(map(int, input().split()))
	idx = n - 1
	e = []
	vis = [-1] * len(a)
	cost = [0] * (2 * n + 4)
	root = rec(list(range(n)))
	print(idx + 1)
	print(*cost[:idx + 1])
	print(root + 1)
	for (u, v) in e:
		print(u + 1, v + 1)
solve()