To learn as soon as possible the latest news about their favourite fundamentally new operating system, BolgenOS community from Nizhni Tagil decided to develop a scheme. According to this scheme a community member, who is the first to learn the news, calls some other member, the latter, in his turn, calls some third member, and so on; i.e. a person with index i got a person with index fi, to whom he has to call, if he learns the news. With time BolgenOS community members understood that their scheme doesn't work sometimes — there were cases when some members didn't learn the news at all. Now they want to supplement the scheme: they add into the scheme some instructions of type (xi, yi), which mean that person xi has to call person yi as well. What is the minimum amount of instructions that they need to add so, that at the end everyone learns the news, no matter who is the first to learn it?

Input

The first input line contains number n (2 ≤ n ≤ 105) — amount of BolgenOS community members. The second line contains n space-separated integer numbers fi (1 ≤ fi ≤ n, i ≠ fi) — index of a person, to whom calls a person with index i.

Output

In the first line output one number — the minimum amount of instructions to add. Then output one of the possible variants to add these instructions into the scheme, one instruction in each line. If the solution is not unique, output any.

Examples

Input

3
3 3 2


Output

1
3 1


Input

7
2 3 1 3 4 4 1


Output

3
2 5
2 6
3 7

Source: codeforces | Difficulty: HARD
Tags: Tree algorithms

Graph algorithms

Graph traversal


Solutions:
import sys
n = int(input())
g = [int(i) - 1 for i in sys.stdin.readline().split()]

def solve(n, g):
	vertex_id = [-1] * n
	current_id = 0
	cycle_starts = []
	cycle_starts_by_vertex = [-1] * n
	cycle_vertex_sample = []
	start_on_cycle = []
	cycle_index_by_ID = []
	for v in range(n):
		if vertex_id[v] != -1:
			continue
		current_vertex = v
		cycle_found = False
		while vertex_id[current_vertex] == -1:
			vertex_id[current_vertex] = current_id
			current_vertex = g[current_vertex]
			if vertex_id[current_vertex] == current_id:
				cycle_found = True
				cycle_vertex_sample.append(current_vertex)
				start_on_cycle.append(current_vertex == v)
		if not cycle_found:
			if cycle_starts_by_vertex[current_vertex] != -1:
				cycle_starts_by_vertex[v] = cycle_starts_by_vertex[current_vertex]
				cycle_starts_by_vertex[current_vertex] = -1
			cycle_index_by_ID.append(cycle_index_by_ID[vertex_id[current_vertex]])
			cycle = cycle_index_by_ID[-1]
			if start_on_cycle[cycle]:
				cycle_starts_by_vertex[cycle_vertex_sample[cycle]] = -1
				start_on_cycle[cycle] = False
			cycle_starts_by_vertex[v] = cycle
		else:
			cycle_starts_by_vertex[v] = len(cycle_vertex_sample) - 1
			cycle_index_by_ID.append(len(cycle_vertex_sample) - 1)
		current_id += 1
	cycle_starts = [[] for _ in range(len(cycle_vertex_sample))]
	for i in range(n):
		if cycle_starts_by_vertex[i] != -1:
			cycle_starts[cycle_starts_by_vertex[i]].append(i)
	expanded = []
	for i in range(len(cycle_vertex_sample)):
		v = cycle_vertex_sample[i]
		for u in cycle_starts[i]:
			expanded.append([v, u])
	if len(expanded) == 1 and expanded[0][0] == expanded[0][1]:
		print(0)
	else:
		ans = []
		for i in range(len(expanded) - 1):
			v = expanded[i][0]
			u = expanded[i + 1][1]
			ans.append('{0} {1}'.format(v + 1, u + 1))
		ans.append('{0} {1}'.format(expanded[-1][0] + 1, expanded[0][1] + 1))
		print(len(ans))
		print('\n'.join(ans))
solve(n, g)


n = int(input())
f = map(int, input().split())
f = [d - 1 for d in f]
indegree = [0 for i in range(n)]
for i in range(n):
	indegree[f[i]] += 1
endpoints = [i for i in range(n) if indegree[i] == 0]
nr_indegree_zero = len(endpoints)
unvisited = set(range(n))
reach = [None for i in range(n)]

def determine_reach(v):
	path = [v]
	while v in unvisited:
		unvisited.remove(v)
		v = f[v]
		path.append(v)
	for i in path:
		reach[i] = v
for v in endpoints:
	determine_reach(v)
startpoints = [reach[v] for v in endpoints]
nr_cycles = 0
while len(unvisited) > 0:
	v = unvisited.pop()
	unvisited.add(v)
	nr_cycles += 1
	determine_reach(v)
	endpoints.append(v)
	startpoints.append(reach[v])
if nr_indegree_zero == 0 and nr_cycles == 1:
	print(0)
	exit()
endpoints = endpoints[1:] + endpoints[:1]
print(len(startpoints))
print('\n'.join(['%d %s' % (start + 1, end + 1) for (start, end) in zip(startpoints, endpoints)]))


def dfs_1(graph):
	n = len(graph)
	stack = []
	recursive_stack = []
	status = [[False, 0] for i in range(n)]
	for i in range(n):
		if not status[i][0]:
			recursive_stack.append(i)
			status[i][0] = True
			__dfs(graph, status, stack, recursive_stack)
	return stack

def __dfs(graph, status, stack, recursive_stack):
	while len(recursive_stack):
		vert = recursive_stack.pop()
		if status[vert][1] != len(graph[vert]):
			act = graph[vert][status[vert][1]]
			status[vert][1] += 1
			if not status[act][0]:
				status[act][0] = True
				recursive_stack.append(vert)
				recursive_stack.append(act)
			else:
				recursive_stack.append(vert)
		else:
			stack.append(vert)

def reverse_graph(graph):
	n = len(graph)
	new_graph = [[] for i in range(n)]
	pos = 0
	for i in graph:
		for j in i:
			new_graph[j].append(pos)
		pos += 1
	return new_graph

def dfs_2(graph, stack):
	n = len(graph)
	status = [[False, 0] for i in range(n)]
	scc = 0
	dag = [-1 for i in range(n)]
	recursive_stack = []
	while len(stack) > 0:
		root = stack.pop()
		if not status[root][0]:
			__dfs_2(graph, status, scc, dag, root, recursive_stack)
			scc += 1
	return (scc, dag)

def __dfs_2(graph, status, scc, dag, root, recursive_stack):
	status[root][0] = True
	recursive_stack.append(root)
	while len(recursive_stack):
		vert = recursive_stack.pop()
		if status[vert][1] != len(graph[vert]):
			act = graph[vert][status[vert][1]]
			status[vert][1] += 1
			if not status[act][0]:
				status[act][0] = True
				recursive_stack.append(vert)
				recursive_stack.append(act)
			else:
				recursive_stack.append(vert)
		else:
			dag[vert] = scc

def SCC(graph):
	stack = dfs_1(graph)
	rvgraph = reverse_graph(graph)
	return dfs_2(rvgraph, stack)

def get_dag_degrees(graph):
	(n_scc, GSCC) = SCC(graph)
	dag = [[] for i in range(n_scc)]
	degres = [[0, 0] for i in range(n_scc)]
	count = 0
	for i in graph:
		for j in i:
			if GSCC[count] != GSCC[j]:
				dag[GSCC[count]].append(GSCC[j])
				degres[GSCC[count]][1] += 1
				degres[GSCC[j]][0] += 1
		count += 1
	return (dag, degres, GSCC, n_scc)

def part_degrees(degrees):
	in_degree = []
	cout = 0
	for i in degrees:
		if i[0] == 0:
			in_degree.append(cout)
		cout += 1
	return in_degree

def solve(graph):
	(dag, degrees, GSCC, n_scc) = get_dag_degrees(graph)
	if n_scc == 1:
		print(0)
		return
	mapping = [-1 for i in range(len(dag))]
	in_degree = part_degrees(degrees)
	for i in range(len(graph)):
		if mapping[GSCC[i]] == -1:
			mapping[GSCC[i]] = i
	status = [[False, 0] for i in range(len(dag))]
	current_info = [0, -1]
	recursive_stack = []
	upd_arcs = []
	last_vert = [-1]
	for i in in_degree:
		if not status[i][0]:
			if last_vert[0] != -1:
				current_info[0] += 1
				upd_arcs.append((last_vert[0], i))
			__dfs_solve(dag, status, degrees, upd_arcs, i, current_info, last_vert, recursive_stack)
			current_info[1] = -1
	upd_arcs.append((last_vert[0], in_degree[0]))
	current_info[0] += 1
	print(current_info[0])
	for i in upd_arcs:
		print(mapping[i[0]] + 1, mapping[i[1]] + 1)

def __dfs_solve(graph, status, degrees, upd_arcs, root, current_info, last_vert, recursive_stack):
	status[root][0] = True
	recursive_stack.append(root)
	while len(recursive_stack):
		vert = recursive_stack.pop()
		if status[vert][1] != len(graph[vert]):
			act = graph[vert][status[vert][1]]
			status[vert][1] += 1
			if not status[act][0]:
				status[act][0] = True
				recursive_stack.append(vert)
				recursive_stack.append(act)
			else:
				recursive_stack.append(vert)
		elif degrees[vert][1] == 0:
			if current_info[1] != -1:
				current_info[0] += 1
				upd_arcs.append((current_info[1], vert))
			current_info[1] = last_vert[0] = vert
n = int(input())
graph = [[] for i in range(n)]
data_set = input().split()
for i in range(n):
	graph[i].append(int(data_set[i]) - 1)
solve(graph)


n = int(input())
g = [int(i) - 1 for i in input().split()]

def solve(n, g):
	vertex_id = [-1] * n
	current_id = 0
	starts_a_cycle = [-1] * n
	cycle_vertex_sample = []
	start_on_cycle = []
	cycle_index_by_ID = []
	cycle_count = 0
	for v in range(n):
		if vertex_id[v] != -1:
			continue
		current_vertex = v
		cycle_found = False
		while vertex_id[current_vertex] == -1:
			vertex_id[current_vertex] = current_id
			current_vertex = g[current_vertex]
			if vertex_id[current_vertex] == current_id:
				cycle_found = True
				cycle_count += 1
				cycle_vertex_sample.append(current_vertex)
				start_on_cycle.append(current_vertex == v)
		if not cycle_found:
			if starts_a_cycle[current_vertex] != -1:
				starts_a_cycle[v] = starts_a_cycle[current_vertex]
				starts_a_cycle[current_vertex] = -1
			cycle_index_by_ID.append(cycle_index_by_ID[vertex_id[current_vertex]])
			cycle = cycle_index_by_ID[-1]
			if start_on_cycle[cycle]:
				starts_a_cycle[cycle_vertex_sample[cycle]] = -1
				start_on_cycle[cycle] = False
			starts_a_cycle[v] = cycle
		else:
			starts_a_cycle[v] = cycle_count - 1
			cycle_index_by_ID.append(cycle_count - 1)
		current_id += 1
	expanded = []
	for i in range(n):
		if starts_a_cycle[i] != -1:
			cycle = starts_a_cycle[i]
			v = cycle_vertex_sample[cycle]
			expanded.append([v, i])
	if len(expanded) == 1 and expanded[0][0] == expanded[0][1]:
		print(0)
		return
	print(len(expanded))
	for i in range(len(expanded) - 1):
		(v, u) = (expanded[i][0], expanded[i + 1][1])
		print('{0} {1}'.format(v + 1, u + 1))
	print('{0} {1}'.format(expanded[-1][0] + 1, expanded[0][1] + 1))
solve(n, g)


import sys
from array import array

def input():
	return sys.stdin.buffer.readline().decode('utf-8')
n = int(input())
a = [0] + list(map(int, input().split()))
rev = [[] for _ in range(n + 1)]
indeg = [0] * (n + 1)
for i in range(1, n + 1):
	indeg[a[i]] += 1
	rev[a[i]].append(i)
_indeg = indeg[:]
for i in range(1, n + 1):
	if _indeg[i]:
		continue
	v = i
	while indeg[v] == 0:
		indeg[a[v]] -= 1
		v = a[v]
visited = [0] * (n + 1)
group = []
group_leaf = []
for i in range(1, n + 1):
	if visited[i] or indeg[i] == 0:
		continue
	visited[i] = 1
	leaves = []
	stack = [i]
	while stack:
		v = stack.pop()
		if _indeg[v] == 0:
			leaves.append(v)
		for dest in rev[v]:
			if not visited[dest]:
				visited[dest] = 1
				stack.append(dest)
	if not leaves:
		leaves.append(i)
	group.append(i)
	group_leaf.append(leaves)
assert all(visited[1:])
ans = []
m = len(group)
if not (m == 1 and group_leaf[0][0] == group[0]):
	for i in range(m):
		k = group[(i + 1) % m]
		for j in group_leaf[i]:
			ans.append(f'{k} {j}')
ans_str = str(len(ans)) + '\n' + '\n'.join(ans)
sys.stdout.buffer.write(ans_str.encode('utf-8'))


import sys
from collections import Counter
input = lambda : sys.stdin.readline().strip()
n = int(input())
f = [0, *(int(x) for x in input().split())]
c = Counter(f)
component = [0 for i in range(n + 1)]
last = [0 for i in range(n + 1)]
roots = [i for i in range(1, n + 1) if i not in c]

def bfs(s):
	q = [s]
	component[s] = s
	for u in q:
		last[component[u]] = f[u]
		if not component[f[u]]:
			component[f[u]] = component[u]
			q.append(f[u])
for s in roots:
	bfs(s)
for s in range(1, n + 1):
	if not component[s]:
		roots.append(s)
		bfs(s)
if len(roots) == 1:
	if last[roots[0]] == roots[0]:
		print(0)
	else:
		print(1)
		print(last[roots[0]], roots[0])
else:
	print(len(roots))
	for i in range(len(roots)):
		print(last[roots[i]], roots[(i + 1) % len(roots)])