import java.io.*;
import java.util.*;

public class Main {

    public static void main(String[] args) throws Exception {
        Scanner sc = new Scanner(System.in);
        PrintWriter out = new PrintWriter(System.out);
        int n = sc.nextInt();
        HashSet<String> arr = new HashSet<String>();
        String[] a = new String[n];
        for(int i=0 ;i<n;i++)
        	a[i]=sc.nextLine();

        for(int i =n-1 ;i>=0 ;i--){
        	if(!arr.contains(a[i])){
        		out.println(a[i]);
        		arr.add(a[i]);
        	}
        }
        out.flush();
    }

    static class Scanner
    {
        StringTokenizer st;
        BufferedReader br;

        public Scanner(InputStream system) {br = new BufferedReader(new InputStreamReader(system));}
        public Scanner(String file) throws Exception {br = new BufferedReader(new FileReader(file));}
        public String next() throws IOException
        {
            while (st == null || !st.hasMoreTokens()) st = new StringTokenizer(br.readLine());
            return st.nextToken();
        }
        public String nextLine()throws IOException{return br.readLine();}
        public int nextInt() throws IOException {return Integer.parseInt(next());}
        public double nextDouble() throws IOException {return Double.parseDouble(next());}
        public char nextChar()throws IOException{return next().charAt(0);}
        public Long nextLong()throws IOException{return Long.parseLong(next());}
        public boolean ready() throws IOException{return br.ready();}
        public void waitForInput() throws InterruptedException {Thread.sleep(3000);}
    }
}


import java.util.HashSet;
import java.util.Scanner;

public class ChatOrder {

	public static void main(String[] args) {
		Scanner scan = new Scanner(System.in);
		int n = scan.nextInt();
		String[] chat = new String[n];
		for(int runs = 0; runs < n; runs++) chat[n-runs-1] = scan.next();
		HashSet<String> used = new HashSet<String>();
		for(int i = 0; i < n; i++)if(!used.contains(chat[i])){ System.out.println(chat[i]); used.add(chat[i]);}
	}

}


import java.util.ArrayList;
import java.util.Scanner;

public class ChatOrder {

	public static void main(String[] args) {
		Scanner scan = new Scanner(System.in);
		int n = scan.nextInt();
		String[] chat = new String[n];
		for(int runs = 0; runs < n; runs++) chat[n-runs-1] = scan.next();
		ArrayList<String> used = new ArrayList<String>();
		for(int i = 0; i < n; i++){
			if(!used.contains(chat[i])){ System.out.println(chat[i]); used.add(chat[i]);}
		}
	}

}


import java.util.ArrayList;
import java.util.Scanner;

public class ChatOrder {

	public static void main(String[] args) {
		Scanner scan = new Scanner(System.in);
		int n = scan.nextInt();
		ArrayList<String> chat = new ArrayList<String>();
		for(int runs = 0; runs < n; runs++){
			String temp = scan.next();
			if(!chat.contains(temp)) chat.add(temp);
			else for(int i = 0; i < chat.size(); i++) if(chat.get(i).equals(temp)){chat.remove(i); chat.add(temp); break;}
		}
		for(int i = chat.size()-1; i >= 0; i--) System.out.println(chat.get(i));
	}

}


import java.util.Scanner;

public class Voting {

	public static void main(String[] args) {
		Scanner scan = new Scanner(System.in);
		int[] a = new int[100001];
		int n = scan.nextInt(), max = 0, index = 0;
		while(n --> 0){
			int i = scan.nextInt();
			a[i]++;
			if(a[i] > max){max = a[i]; index = i;}
		}
		System.out.println(index);
	}

}


import java.util.Scanner;
import java.util.Stack;

public class chatorder {
	public static void main (String args[]){
		Scanner s = new Scanner(System.in);
		Stack<String> st = new Stack<String>();
		int i =s.nextInt();
		for(int a= 0; a<i; a++){
			String name = s.next();

		if(st.isEmpty())
			st.push(name);
		else if(st.contains(name)){
			st.remove(name);st.trimToSize();
			st.push(name);
		}
		else{
			st.push(name);
		}
		}
		while(!st.isEmpty()){
			System.out.println(st.pop());
		}
		}
}


import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Scanner;
import java.util.Set;

public class chatorder {
	public static void main (String args[]){
		Scanner s = new Scanner(System.in);
		//HashMap map = new HashMap();
		HashMap<Integer,String> st = new HashMap <Integer,String>();
		int i =s.nextInt(); int key=0;
		for(int a= 0; a<i; a++){
			String name = s.next();
		if (st.isEmpty())
			st.put(a,name);

		else if(st.containsValue(name)){
			Set<Entry<Integer, String>> set2 = st.entrySet();
		      Iterator<Entry<Integer, String>> iterator = set2.iterator();

		      while(iterator.hasNext()) {
		          Map.Entry mentry = (Map.Entry)iterator.next();
		          if(mentry.getValue().equals(name))
		        	  key= (Integer) mentry.getKey();

		       }

			System.err.println(name);
			st.remove(key);
			st.put(a,name);
		}
		else{
			st.put(a,name);
		}
		}
		Set<Entry<Integer, String>> set2 = st.entrySet();
	      Iterator<Entry<Integer, String>> iterator2 = set2.iterator();
	      while(iterator2.hasNext()) {
	          Map.Entry mentry2 = (Map.Entry)iterator2.next();
	          System.out.println(mentry2.getValue());
	       }

	   }
}


import java.util.*;
import java.util.Map.Entry;

public class chatorder {
	public static void main (String args[]){
		Scanner s = new Scanner(System.in);
		//HashMap map = new HashMap();
		HashMap<Integer,String> st = new HashMap <Integer,String>();
		//Map<Integer, String> st = new TreeMap<Integer, String>(Collections.reverseOrder());
		int i =s.nextInt(); int key=0;
		for(int a= 0; a<i; a++){
			String name = s.next();

			st.put(a,name);
		}

	Map<Integer, String> st3 = new TreeMap<Integer, String>(Collections.reverseOrder());

st3.putAll(st);

LinkedHashSet<String> st2 = new LinkedHashSet<String>();
st2.addAll(st3.values());
for (String value : st2) {
		    System.out.println(value);
}
}}


import java.util.ArrayList;
import java.util.Scanner;
import java.util.Stack;

public class chatorder {
	public static void main (String args[]){
		Scanner s = new Scanner(System.in);
		ArrayList<String> st = new ArrayList<String>();
		int i =s.nextInt();
		for(int a= 0; a<i; a++){
			String name = s.next();
		if(st.isEmpty())
			st.add(name);
		else if(st.contains(name)){
			st.remove(name);
			st.add(name);
		}
		else{
			st.add(name);
		}
		}
		for(int a= st.size()-1; a>=0; a--){
			System.out.println(st.get(a));
		}
}
}


import java.util.*;
import java.io.*;
public class draft {
	public static void main(String args[]) throws IOException
	{//Scan s= new Scan();
		FastScanner s = new FastScanner();
	Print print = new Print();
	int n = s.nextInt();
	LinkedHashSet<String> hs = new LinkedHashSet<String>();
	//TreeSet<String> hs = new TreeSet<String>();
	for(int a=0;a<n;a++){StringBuilder sb = new StringBuilder(s.nextToken());
if(!hs.add(sb.toString())){
	hs.remove(sb.toString());
	hs.add(sb.toString());
}
	}
	List<String> list = new ArrayList<String>(hs);
	Collections.reverse((List<?>) list);
	//System.out.println(list.toString().replace("[", "").replace("]", "").replaceAll(", ", "\n"));
	print.print(list.toString().replace("[", "").replace("]", "").replaceAll(", ", "\n"));

		print.close();

	}

}
class Print
{
    private final BufferedWriter bw;
    public Print()
    {
        this.bw=new BufferedWriter(new OutputStreamWriter(System.out));
    }
    public void print(Object object)throws IOException
    {
        bw.append(""+object);
    }
    public void println(Object object)throws IOException
    {
        print(object);
        bw.append("\n");
    }
    public void close()throws IOException
    {
        bw.close();
    }
}

class FastScanner {
	BufferedReader br;
	StringTokenizer st;

	public FastScanner(String s) {
		try {
			br = new BufferedReader(new FileReader(s));
		} catch (FileNotFoundException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

	public FastScanner() {
		br = new BufferedReader(new InputStreamReader(System.in));
	}

	String nextToken() {
		while (st == null || !st.hasMoreElements()) {
			try {
				st = new StringTokenizer(br.readLine());
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
		return st.nextToken();
	}

	int nextInt() {
		return Integer.parseInt(nextToken());
	}

	long nextLong() {
		return Long.parseLong(nextToken());
	}

	double nextDouble() {
		return Double.parseDouble(nextToken());
	}
}

	class Scan
	{
	    private byte[] buf=new byte[1024];    //Buffer of Bytes
	    private int index;
	    private InputStream in;
	    private int total;
	    public Scan()
	    {
	        in=System.in;
	    }
	    public int scan()throws IOException    //Scan method used to scan buf
	    {
	        if(total<0)
	        throw new InputMismatchException();
	        if(index>=total)
	        {
	            index=0;
	            total=in.read(buf);
	            if(total<=0)
	            return -1;
	        }
	        return buf[index++];
	    }
	    public int scanInt()throws IOException
	    {
	        int integer=0;
	        int n=scan();
	        while(isWhiteSpace(n))    //Removing starting whitespaces
	        n=scan();
	        int neg=1;
	        if(n=='-')                //If Negative Sign encounters
	        {
	            neg=-1;
	            n=scan();
	        }
	        while(!isWhiteSpace(n))
	        {
	            if(n>='0'&&n<='9')
	            {
	                integer*=10;
	                integer+=n-'0';
	                n=scan();
	            }
	            else throw new InputMismatchException();
	        }
	        return neg*integer;
	    }
	    private boolean isWhiteSpace(int n)
	    {
	        if(n==' '||n=='\n'||n=='\r'||n=='\t'||n==-1)
	        return true;
	        return false;
	    }
	}


import java.util.LinkedList;
import java.util.Scanner;

public class chatorder {
	public static void main (String args[]){
		Scanner s = new Scanner(System.in);
		LinkedList<String> st = new LinkedList<String>();
		int i =s.nextInt();
		for(int a= 0; a<i; a++){
			String name = s.next();
		if(st.isEmpty())
			st.addLast(name);
		else if(st.contains(name)){
			st.remove(name);
			st.addLast(name);
		}
		else{
			st.addLast(name);
		}
		}
		for(int a= st.size()-1; a>=0; a--){
			System.out.println(st.removeLast());
		}
}
}


import java.util.*;
import java.io.*;
public class draft {
	public static void main(String args[]) throws IOException
	{//Scan s= new Scan();
		//FastScanner s = new FastScanner();
	BufferedReader br = new BufferedReader(new InputStreamReader(System.in));

		Print print = new Print();
	int n = Integer.parseInt(br.readLine());
	LinkedHashSet<String> hs = new LinkedHashSet<String>();
	//TreeSet<String> hs = new TreeSet<String>();
	for(int a=0;a<n;a++){StringBuilder sb = new StringBuilder(br.readLine());
if(!hs.add(sb.toString())){
	hs.remove(sb.toString());
	hs.add(sb.toString());
}
	}
	List<String> list = new ArrayList<String>(hs);
	Collections.reverse((List<?>) list);
	//System.out.println(list.toString().replace("[", "").replace("]", "").replaceAll(", ", "\n"));
	print.print(list.toString().replace("[", "").replace("]", "").replaceAll(", ", "\n"));

		print.close();

	}

}
class Print
{
    private final BufferedWriter bw;
    public Print()
    {
        this.bw=new BufferedWriter(new OutputStreamWriter(System.out));
    }
    public void print(Object object)throws IOException
    {
        bw.append(""+object);
    }
    public void println(Object object)throws IOException
    {
        print(object);
        bw.append("\n");
    }
    public void close()throws IOException
    {
        bw.close();
    }
}

class FastScanner {
	BufferedReader br;
	StringTokenizer st;

	public FastScanner(String s) {
		try {
			br = new BufferedReader(new FileReader(s));
		} catch (FileNotFoundException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

	public FastScanner() {
		br = new BufferedReader(new InputStreamReader(System.in));
	}

	String nextToken() {
		while (st == null || !st.hasMoreElements()) {
			try {
				st = new StringTokenizer(br.readLine());
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
		return st.nextToken();
	}

	int nextInt() {
		return Integer.parseInt(nextToken());
	}

	long nextLong() {
		return Long.parseLong(nextToken());
	}

	double nextDouble() {
		return Double.parseDouble(nextToken());
	}
}

	class Scan
	{
	    private byte[] buf=new byte[1024];    //Buffer of Bytes
	    private int index;
	    private InputStream in;
	    private int total;
	    public Scan()
	    {
	        in=System.in;
	    }
	    public int scan()throws IOException    //Scan method used to scan buf
	    {
	        if(total<0)
	        throw new InputMismatchException();
	        if(index>=total)
	        {
	            index=0;
	            total=in.read(buf);
	            if(total<=0)
	            return -1;
	        }
	        return buf[index++];
	    }
	    public int scanInt()throws IOException
	    {
	        int integer=0;
	        int n=scan();
	        while(isWhiteSpace(n))    //Removing starting whitespaces
	        n=scan();
	        int neg=1;
	        if(n=='-')                //If Negative Sign encounters
	        {
	            neg=-1;
	            n=scan();
	        }
	        while(!isWhiteSpace(n))
	        {
	            if(n>='0'&&n<='9')
	            {
	                integer*=10;
	                integer+=n-'0';
	                n=scan();
	            }
	            else throw new InputMismatchException();
	        }
	        return neg*integer;
	    }
	    private boolean isWhiteSpace(int n)
	    {
	        if(n==' '||n=='\n'||n=='\r'||n=='\t'||n==-1)
	        return true;
	        return false;
	    }
	}


import java.util.*;
import java.util.Map.Entry;

public class chatorder {
	public static void main (String args[]){
		Scanner s = new Scanner(System.in);
		//HashMap map = new HashMap();
		//HashMap<Integer,String> st = new HashMap <Integer,String>();
		Map<Integer, String> st = new TreeMap<Integer, String>(Collections.reverseOrder());
		int i =s.nextInt(); int key=0;
		for(int a= 0; a<i; a++){
			String name = s.next();
		if (st.isEmpty())
			st.put(a,name);

		else if(st.containsValue(name)){
			Set<Entry<Integer, String>> set2 = st.entrySet();
		      Iterator<Entry<Integer, String>> iterator = set2.iterator();
		      Boolean flag = true;
		      while(iterator.hasNext()&&flag) {
		          Map.Entry mentry = (Map.Entry)iterator.next();
		          if(mentry.getValue().equals(name)){
		      iterator.remove();
		      flag=false;}
		       }
			st.put(a,name);
		}
		else{
			st.put(a,name);
		}
		}
		/*Map<Integer, String> st = new TreeMap<Integer, String>(Collections.reverseOrder());
		for (Map.Entry<Integer, String> entry : st.entrySet()) {
		    items.put(entry.getKey(), entry.getValue());
		}*/
		for (String value : st.values()) {
		    System.out.println(value);
		}
}}


import java.util.ArrayList;
import java.util.Scanner;
import java.util.Stack;

public class chatorder {
	public static void main (String args[]){
		Scanner s = new Scanner(System.in);
		Stack<String> st = new Stack<String>();
		st.contains("");
		int i =s.nextInt();
		for(int a= 0; a<i; a++){
			String name = s.next();

		if(st.isEmpty())
			st.push(name);
		else if(st.contains(name)){
			st.remove(name);
			st.push(name);
		}
		else{
			st.push(name);
		}
		}
		while(!st.isEmpty()){
			System.out.println(st.pop());
		}
		}
}


import java.util.*;
import java.util.Map.Entry;

public class chatorder {
	public static void main (String args[]){
		Scanner s = new Scanner(System.in);
		//HashMap map = new HashMap();
		HashMap<Integer,String> st = new HashMap <Integer,String>();
		HashMap<Object, Object> ss = new HashMap<Object, Object>();
		int i =s.nextInt(); int key=0;
		for(int a= 0; a<i; a++){
			String name = s.next();
		if (st.isEmpty())
			st.put(a,name);

		else if(st.containsValue(name)){
			Set<Entry<Integer, String>> set2 = st.entrySet();
		      Iterator<Entry<Integer, String>> iterator = set2.iterator();

		      while(iterator.hasNext()) {
		          Map.Entry mentry = (Map.Entry)iterator.next();
		          if(mentry.getValue().equals(name))
		        	  key= (Integer) mentry.getKey();

		       }
			st.remove(key);
			st.put(a,name);
		}
		else{
			st.put(a,name);
		}
		}
		Map<Integer, String> items = new TreeMap<Integer, String>(Collections.reverseOrder());
		for (Map.Entry<Integer, String> entry : st.entrySet()) {
		    items.put(entry.getKey(), entry.getValue());
		}
		for (String value : items.values()) {
		    System.out.println(value);
		}
}}


import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.util.Collections;
import java.util.PriorityQueue;
import java.util.TreeMap;
import java.util.TreeSet;

public class chatOrderCF637B {
	public static void main (String[] args) throws Exception {
		BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
		PrintWriter out = new PrintWriter(System.out);
		int n = Integer.parseInt(br.readLine());
		//TreeMap<String, Integer> tm = new TreeMap<>();
		TreeMap<String,EXpa> tmp = new TreeMap<>();
		for(int i=0;i<n;i++) {
			String m = br.readLine();
			if(tmp.containsKey(m)) {
				tmp.get(m).incOcc();
			}
			else {
				tmp.put(m, new EXpa(m,1));
			}

		}
		PriorityQueue<EXpa> pq = new PriorityQueue<>(Collections.reverseOrder());
		for (EXpa p : tmp.values()) {
			pq.add(p);
		}
		while(!pq.isEmpty()) {
			out.println(pq.poll());
		}

		out.close();
		br.close();
	}
}
class EXpa implements Comparable{
	String name;
	int occ;
	public EXpa(String name,int occ) {
		this.name=name;this.occ=occ;
	}
	public int compareTo(Object o) {
		EXpa p = (EXpa) o;
		return occ-p.occ;
	}
	public void incOcc() {
		occ++;
	}
	public int getOcc() {
		return occ;
	}
	public String toString() {
		return name;
	}

}


import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.util.Collections;
import java.util.PriorityQueue;
import java.util.TreeMap;
import java.util.TreeSet;

public class chatOrderCF637B {
	public static void main (String[] args) throws Exception {
		BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
		PrintWriter out = new PrintWriter(System.out);
		int n = Integer.parseInt(br.readLine());
		//TreeMap<String, Integer> tm = new TreeMap<>();
		TreeMap<String,EXpa> tmp = new TreeMap<>();
		for(int i=0;i<n;i++) {
			String m = br.readLine();
			if(tmp.containsKey(m)) {
				tmp.get(m).incOcc();
			}
			else {
				tmp.put(m, new EXpa(m,1));
			}

		}
		PriorityQueue<EXpa> pq = new PriorityQueue<>(Collections.reverseOrder());
		for (EXpa p : tmp.values()) {
			pq.add(p);
		}
		while(!pq.isEmpty()) {
			out.println(pq.poll());
		}

		out.close();
		br.close();
	}
}
class EXpa implements Comparable{
	String name;
	int occ;
	int age ;
	static int num =0;
	public EXpa(String name,int occ) {
		this.name=name;this.occ=occ;
		age=num++;
	}
	public int compareTo(Object o) {
		EXpa p = (EXpa) o;
		return age-p.age;
	}
	public void incOcc() {
		occ++;
		age= num++;
	}
	public int getOcc() {
		return occ;
	}
	public String toString() {
		return name;
	}

}


import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.util.Collections;
import java.util.PriorityQueue;
import java.util.TreeMap;
import java.util.TreeSet;

public class chatOrderCF637B {
	public static void main (String[] args) throws Exception {
		BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
		PrintWriter out = new PrintWriter(System.out);
		int n = Integer.parseInt(br.readLine());
		TreeMap<String,EXpa> tmp = new TreeMap<>();
		for(int i=0;i<n;i++) {
			String m = br.readLine();
			if(tmp.containsKey(m)) {
				tmp.get(m).incOcc();
			}
			else {
				tmp.put(m, new EXpa(m,1));
			}

		}
		PriorityQueue<EXpa> pq = new PriorityQueue<>(Collections.reverseOrder());
		for (EXpa p : tmp.values()) {
			pq.add(p);
		}
		while(!pq.isEmpty()) {
			out.println(pq.poll());
		}

		out.close();
		br.close();
	}
}
class EXpa implements Comparable{
	String name;
	int occ;
	int age ;
	static int num =0;
	public EXpa(String name,int occ) {
		this.name=name;this.occ=occ;
		age=num++;
	}
	public int compareTo(Object o) {
		EXpa p = (EXpa) o;
		return age-p.age;
	}
	public void incOcc() {
		occ++;
		age= num++;
	}
	public int getOcc() {
		return occ;
	}
	public String toString() {
		return name;
	}

}


import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.util.Collections;
import java.util.PriorityQueue;
import java.util.TreeMap;
import java.util.TreeSet;

public class chatOrderCF637B {
	public static void main (String[] args) throws Exception {
		BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
		PrintWriter out = new PrintWriter(System.out);
		int n = Integer.parseInt(br.readLine());
		//TreeMap<String, Integer> tm = new TreeMap<>();
		TreeMap<String,EXpa> tmp = new TreeMap<>();
		for(int i=0;i<n;i++) {
			String m = br.readLine();
			if(tmp.containsKey(m)) {
				tmp.get(m).incOcc();
			}
			else {
				tmp.put(m, new EXpa(m,1));
			}

		}
		PriorityQueue<EXpa> pq = new PriorityQueue<>();
		for (EXpa p : tmp.values()) {
			pq.add(p);
		}
		while(!pq.isEmpty()) {
			out.println(pq.poll());
		}

		out.close();
		br.close();
	}
}
class EXpa implements Comparable{
	String name;
	int occ;
	int age ;
	static int num =0;
	public EXpa(String name,int occ) {
		this.name=name;this.occ=occ;
		age=num++;
	}
	public int compareTo(Object o) {
		EXpa p = (EXpa) o;
		return age-p.age;
	}
	public void incOcc() {
		occ++;
	}
	public int getOcc() {
		return occ;
	}
	public String toString() {
		return name;
	}

}


import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.util.Comparator;
import java.util.HashMap;
import java.util.Map;
import java.util.TreeMap;

/**
 * Created by himanshubhardwaj on 06/06/19.
 */
public class ChatOrder {
    public static void main(String[] args) throws IOException {
        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
        int n = Integer.parseInt(br.readLine());
        HashMap<String, Integer> hashMap = new HashMap<>();

        for (int i = 0; i < n; i++) {
            String str = br.readLine();
            hashMap.put(str, i);
        }

        Comparator<Integer> comparator = new Comparator<Integer>() {
            @Override
            public int compare(Integer o1, Integer o2) {
                return o2.compareTo(o1);
            }
        };

        TreeMap<Integer, String> reverseMAp = new TreeMap<>(comparator);

        for (Map.Entry<String, Integer> entry : hashMap.entrySet()) {
            reverseMAp.put(entry.getValue(), entry.getKey());
        }

        PrintWriter pw = new PrintWriter(System.out);
        for (Map.Entry<Integer, String> entry : reverseMAp.entrySet()) {
            pw.append(entry.getValue());
            pw.append("\n");
        }
        pw.flush();
    }
}


import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.util.Comparator;
import java.util.HashMap;
import java.util.Map;
import java.util.TreeMap;

/**
 * Created by himanshubhardwaj on 06/06/19.
 */
public class ChatOrder {
    public static void main(String[] args) throws IOException {
        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
        int n = Integer.parseInt(br.readLine());
        HashMap<String, Integer> hashMap = new HashMap<>();

        for (int i = 0; i < n; i++) {
            String str = br.readLine();
            hashMap.put(str, i);
        }

        Comparator<Integer> comparator = new Comparator<Integer>() {
            @Override
            public int compare(Integer o1, Integer o2) {
                return o2.compareTo(o1);
            }
        };

        TreeMap<Integer, String> reverseMAp = new TreeMap<>(comparator);

        for (Map.Entry<String, Integer> entry : hashMap.entrySet()) {
            reverseMAp.put(entry.getValue(), entry.getKey());
        }

        for (Map.Entry<Integer, String> entry : reverseMAp.entrySet()) {
            System.out.println(entry.getValue());
        }
    }
}


import java.util.ArrayList;
import java.util.Collections;
import java.util.Scanner;

public class Main {

	public static void main(String[] args) {
		ArrayList<String> input = new ArrayList<>();
		ArrayList<String> arr = new ArrayList<>();
		Scanner sc = new Scanner(System.in);
		int t = sc.nextInt();
		for (int i=0;i<t;i++)
			input.add(sc.next());
		Collections.reverse(input);
		for (String s : input) {
			if (!arr.contains(s)) {
				arr.add(s);
				System.out.println(s);
			}
		}

	}
}


import java.util.ArrayList;
import java.util.Scanner;

public class Main {

	public static void main(String[] args) {
		ArrayList<String> arr = new ArrayList<>();
		Scanner sc = new Scanner(System.in);
		int num = sc.nextInt();
		String[] ele = new String[num];
		for (int i=0;i<num;i++)
			ele[i]=sc.next();
		System.out.println(ele.length);
		for (int i=ele.length-1; i>=0;i--) {
			String tmp = ele[i].trim();
			if (!arr.contains(tmp)) {
				arr.add(tmp);
				System.out.println(tmp);
			}
		}

	}
}


import java.util.HashSet;
import java.util.Scanner;

public class Main {

	public static void main(String[] args) {
		HashSet<String> arr = new HashSet<>();
		Scanner sc = new Scanner(System.in);
		int num = sc.nextInt();
		String[] ele = new String[num];
		for (int i=0;i<num;i++)
			ele[i]=sc.next();
		for (int i=ele.length-1; i>=0;i--) {
			String tmp = ele[i].trim();
			if (!arr.contains(tmp)) {
				arr.add(tmp);
				System.out.println(tmp);
			}
		}

	}
}


import java.util.ArrayList;
import java.util.Scanner;

public class Main {

	public static void main(String[] args) {
		ArrayList<String> arr = new ArrayList<>();
		Scanner sc = new Scanner(System.in);
		String[] ele = sc.nextLine().split(" ");
		for (int i=ele.length-1; i>0;i--) {
			if (!arr.contains(ele[i])) {
				arr.add(ele[i]);
				System.out.println(ele[i]);
			}
		}

	}
}


import java.util.ArrayList;
import java.util.Scanner;

public class Main {

	public static void main(String[] args) {
		ArrayList<String> arr = new ArrayList<>();
		Scanner sc = new Scanner(System.in);
		int num = sc.nextInt();
		String[] ele = new String[num];
		for (int i=0;i<num;i++)
			ele[i]=sc.next();
		for (int i=ele.length-1; i>=0;i--) {
			String tmp = ele[i].trim();
			if (!arr.contains(tmp)) {
				arr.add(tmp);
				System.out.println(tmp);
			}
		}

	}
}


import java.util.ArrayList;
import java.util.Scanner;

public class Main {

	public static void main(String[] args) {
		ArrayList<String> arr = new ArrayList<>();
		Scanner sc = new Scanner(System.in);
		sc.nextInt();
		String[] ele = sc.nextLine().split(" ");
		for (int i=ele.length-1; i>0;i--) {
			String tmp = ele[i].trim();
			if (!arr.contains(tmp)) {
				arr.add(tmp);
				System.out.println(tmp);
			}
		}

	}
}


import java.util.ArrayList;
import java.util.Scanner;

public class Main {

	public static void main(String[] args) {
		ArrayList<String> arr = new ArrayList<>();
		Scanner sc = new Scanner(System.in);
		String[] ele = sc.nextLine().split("\\s+");
		for (int i=ele.length-1; i>0;i--) {
			String tmp = ele[i].trim();
			if (!arr.contains(tmp)) {
				arr.add(tmp);
				System.out.println(tmp);
			}
		}

	}
}


import java.util.ArrayList;
import java.util.Scanner;

public class Main {

	public static void main(String[] args) {
		ArrayList<String> arr = new ArrayList<>();
		Scanner sc = new Scanner(System.in);
		sc.nextInt();
		String[] ele = sc.nextLine().split(" ");
		for (int i=ele.length-1; i>0;i--) {
			String tmp = ele[i];
			if (!arr.contains(tmp)) {
				arr.add(tmp);
				System.out.println(tmp);
			}
		}

	}
}


import java.util.ArrayList;
import java.util.Scanner;

public class Main {

	public static void main(String[] args) {
		ArrayList<String> arr = new ArrayList<>();
		Scanner sc = new Scanner(System.in);
		String[] ele = sc.nextLine().split(" ");
		for (int i=ele.length-1; i>0;i--) {
			String tmp = ele[i];
			if (!arr.contains(tmp)) {
				arr.add(tmp);
				System.out.println(tmp);
			}
		}

	}
}


import java.io.*;
import java.util.*;

public class Main {
    public static void main(String[] args) throws FileNotFoundException {
        Scanner in = new Scanner(System.in);
        try (PrintWriter out = new PrintWriter(System.out)) {
            int n = in.nextInt();
            HashMap<String, Integer> have = new HashMap<>();
            String names[] = new String[n];
            for(int i = 0; i < n; ++i){
                names[i] = in.next();
            }
            for(int i = n - 1; i >= 0; --i){
                if(!have.containsKey(names[i])){
                    have.put(names[i], 0);
                    out.println(names[i]);
                }
            }
        }
    }
}


import java.io.*;
import java.util.*;

public class Main {
    public static void main(String[] args) throws FileNotFoundException {
        Scanner in = new Scanner(System.in);
        try (PrintWriter out = new PrintWriter(System.out)) {
            int n = in.nextInt();
        HashMap<String, Integer> map = new HashMap<>();
        for(int i = 0; i < n; ++i){
            String x = in.next();
            map.put(x, i);
        }
        String nn[] = new String[n];
        for(String name : map.keySet()){
            nn[map.get(name)] = name;
        }
        for(int i = map.size() - 1; i >= 0; --i){
            if(nn[i] != null)
            System.out.println(nn[i]);
        }
        }
    }
}


import java.io.*;
import java.util.*;

public class Main {
    public static void main(String[] args) throws FileNotFoundException {
        Scanner in = new Scanner(System.in);
        try (PrintWriter out = new PrintWriter(System.out)) {
            int n = in.nextInt();
        HashMap<String, Integer> map = new HashMap<>();
        for(int i = 0; i < n; ++i){
            String x = in.next();
            map.put(x, i);
        }
        String nn[] = new String[n + 1];
        for(String name : map.keySet()){
            nn[map.get(name)] = name;
        }
        for(int i = map.size(); i >= 0; --i){
            if(nn[i] != null)
            out.println(nn[i]);
        }
        }
    }
}


import java.io.*;
import java.util.*;

public class Main {
    public static void main(String[] args) throws FileNotFoundException {
        Scanner in = new Scanner(System.in);
        try (PrintWriter out = new PrintWriter(System.out)) {
            int n = in.nextInt();
        HashMap<String, Integer> map = new HashMap<>();
        for(int i = 0; i < n; ++i){
            String x = in.next();
            map.put(x, i);
        }
        String nn[] = new String[map.size()];
        for(String name : map.keySet()){
            nn[map.get(name) - map.size()] = name;
        }
        for(int i = map.size() - 1; i >= 0; --i){
            System.out.println(nn[i]);
        }
        }
    }
}


/**
 *    author:  woodyinho
 **/

import java.util.Scanner;
import java.util.Stack;
import java.util.TreeSet;

public class Main {
    public static void main(String[] args) {
        Scanner in = new Scanner(System.in);
        StringBuilder sb = new StringBuilder();
        int n = in.nextInt();
        TreeSet<String> st = new TreeSet<>();
        Stack<String> sk = new Stack<>();
        Stack<String> sk2 = new Stack<>();
        for(int i=0; i<n; ++i){
            String s = in.next();
            if(!st.contains(s)){
                st.add(s);
                sk.push(s);
            }else sk2.push(s);

        }
       while (!sk2.isEmpty()){
           String s = sk2.peek();
           st.remove(s);
            System.out.println(s);
            sk2.pop();
       }
       while (!sk.isEmpty()){
           String s = sk.peek();
           if(st.contains(s)){
               System.out.println(s);
               sk.pop();
               st.remove(s);
           }else sk.pop();
       }
    }

   static class pair implements Comparable<pair> {
        int s, p, r;

        pair(int x, int y) {
            s = x;
            p = y;
        }

        @Override
        public int compareTo(pair o) {
            // TODO Auto-generated method stub
            if (s != o.s) return o.s - s;
            return p - o.p;
        }
    }
}


/**
 *    author:  woodyinho
 **/

import java.util.Scanner;
import java.util.TreeSet;

public class Main {
    public static void main(String[] args) {
        Scanner in = new Scanner(System.in);
        StringBuilder sb = new StringBuilder();
        int n = in.nextInt();
        String A[] = new String[n+1];
        for(int i=0; i<n; ++i)A[i] = in.next();
        TreeSet<String> st = new TreeSet<>();
        for(int i=n-1; i>=0; --i){
            if(!st.contains(A[i])) System.out.println(A[i]);
            st.add(A[i]);
        }

    }

   static class pair implements Comparable<pair> {
        int s, p, r;

        pair(int x, int y) {
            s = x;
            p = y;
        }

        @Override
        public int compareTo(pair o) {
            // TODO Auto-generated method stub
            if (s != o.s) return o.s - s;
            return p - o.p;
        }
    }
}


import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.util.LinkedList;

public class ChatOrder {
public static void main(String[] args) throws NumberFormatException, IOException {
	BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
	PrintWriter out = new PrintWriter(System.out);
	int n = Integer.parseInt(br.readLine());
	LinkedList a = new LinkedList<>();
	for(int i=0;i<n;i++) {
		String x = br.readLine();
		a.remove(x);
		a.add(x);
	}
	while(!a.isEmpty()) {
		out.println(a.removeLast());
	}
	out.flush();
	out.close();
}
}


import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.util.Stack;

public class ChatOrder {
public static void main(String[] args) throws NumberFormatException, IOException {
	BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
	PrintWriter out = new PrintWriter(System.out);
	int n = Integer.parseInt(br.readLine());
	Stack<String> a= new Stack<>();
	Stack<String> b= new Stack<>();
	for(int i=0;i<n;i++) {
		String x = br.readLine();
		while(!a.isEmpty()) {
			if(a.peek().equals(x)) {
				a.pop();
				break;
			}
			b.push(a.pop());
		}
		while(!b.isEmpty()) {
			a.push(b.pop());
		}
		a.push(x);
	}
	while(!a.isEmpty())
		out.println(a.pop());
	out.flush();
	out.close();
}
}


import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.util.*;

public class ChatOrder {
public static void main(String[] args) throws NumberFormatException, IOException {
	BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
	PrintWriter out = new PrintWriter(System.out);
	int n = Integer.parseInt(br.readLine());
	Stack<String> a = new Stack<>();
	HashSet<String> b = new HashSet<>();
	for(int i=0;i<n;i++) {
		a.push(br.readLine());
	}
	while(!a.isEmpty()) {
		if(!b.contains(a.peek())) {
			out.println(a.peek());
			b.add(a.pop());
		}
		else {
			a.pop();
		}
	}
	out.flush();
	out.close();
}
}


import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.util.*;

public class ChatOrder {
public static void main(String[] args) throws NumberFormatException, IOException {
	BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
	PrintWriter out = new PrintWriter(System.out);
	int n = Integer.parseInt(br.readLine());
	Stack<String> a = new Stack<>();
	HashSet<String> b = new HashSet<>();
	for(int i=0;i<n;i++) {
		a.push(br.readLine());
	}
	while(!a.isEmpty()) {
		if(!b.contains(a.peek())) {
			out.println(a.peek());
			b.add(a.pop());
		}
		else {
			a.pop();
		}
	}
	out.flush();
	out.close();
}
//
}


import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.util.Stack;

public class ChatOrder {
public static void main(String[] args) throws NumberFormatException, IOException {
	BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
	PrintWriter out = new PrintWriter(System.out);
	int n = Integer.parseInt(br.readLine());
	Stack<String> a= new Stack<>();
	Stack<String> b= new Stack<>();
	for(int i=0;i<n;i++) {
		String x = br.readLine();
		if(a.contains(x)) {
		while(!a.isEmpty()) {
			if(a.peek().equals(x)) {
				a.pop();
				break;
			}
			b.push(a.pop());
		}

		while(!b.isEmpty()) {
			a.push(b.pop());
		}
		}
		a.push(x);
	}
	while(!a.isEmpty())
		out.println(a.pop());
	out.flush();
	out.close();
}
}


import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.LinkedList;
import java.util.StringTokenizer;
import java.util.TreeSet;
public class Chat1 {
	public static void main(String[] args) throws IOException, InterruptedException {
		BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
		StringTokenizer st = new StringTokenizer(br.readLine());
		LinkedList<String> l = new LinkedList();
		TreeSet<String> t = new TreeSet<>();
		int n = Integer.parseInt(st.nextToken());
		for(int i=0; i<n ; i++) {
			StringTokenizer st1 = new StringTokenizer(br.readLine());
			String x = st1.nextToken();
			l.addFirst(x);
		}
		for(String y : l) {
			if(!(t.contains(y)))
				System.out.println(y);
			t.add(y);
		}
	}
}


import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.LinkedList;
import java.util.StringTokenizer;
public class Chat1 {
	public static void main(String[] args) throws IOException, InterruptedException {
		BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
		StringTokenizer st = new StringTokenizer(br.readLine());
		LinkedList<String> l = new LinkedList();
		int n = Integer.parseInt(st.nextToken());
		for(int i=0; i<n ; i++) {
			StringTokenizer st1 = new StringTokenizer(br.readLine());
			String x = st1.nextToken();
			if(l.contains(x))
				l.remove(x);
			l.addFirst(x);
		}
		for(String y : l)
			System.out.println(y);
	}
}


import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.LinkedList;
import java.util.StringTokenizer;
import java.util.TreeSet;
public class Chat1 {
	public static void main(String[] args) throws IOException, InterruptedException {
		BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
		StringTokenizer st = new StringTokenizer(br.readLine());
		LinkedList<String> l = new LinkedList();
		TreeSet<String> t = new TreeSet<>();
		int n = Integer.parseInt(st.nextToken());
		for(int i=0; i<n ; i++) {
			StringTokenizer st1 = new StringTokenizer(br.readLine());
			String x = st1.nextToken();
			if(t.contains(x)){
				l.remove(x);
			}
			t.add(x);
			l.addFirst(x);
		}
		for(String y : l)
			System.out.println(y);
	}
}


import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.util.*;

public class Main {

    public static void main(String[] args) throws IOException {
        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
        PrintWriter out = new PrintWriter(System.out);
        int a = Integer.parseInt(br.readLine());

        Stack<String> h = new Stack<>();

        String x;
        for (int i = 0; i < a; i++) {
            x = br.readLine();
            if (h.contains(x)) {
                h.remove(x);
                h.push(x);
            } else {
                h.push(x);
            }
        }
        while (!h.isEmpty())
            out.println(h.pop());

        out.flush();

    }
}


import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.util.*;

public class Main {

    public static void main(String[] args) throws IOException {
        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
        PrintWriter out = new PrintWriter(System.out);
        int a = Integer.parseInt(br.readLine());

        Stack<String> h = new Stack<>();
        TreeMap<String,Integer>shagara=new TreeMap<>();
        TreeMap<Integer,String>shagara2=new TreeMap<>();

        String x;
        for (int i = a; i > 0; i--) {
            x = br.readLine();
           shagara.put(x,i);
        }
        for (Map.Entry <String,Integer>e:shagara.entrySet()) {
            shagara2.put(e.getValue(),e.getKey());

        }
        for (Map.Entry e:shagara2.entrySet()) {
            out.println(e.getValue());

        }

        out.flush();

    }
}


import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.util.*;

public class Main {

    public static void main(String[]args) throws IOException {
        BufferedReader br =new BufferedReader(new InputStreamReader(System.in));
        PrintWriter out =new PrintWriter(System.out);
        int a=Integer.parseInt(br.readLine());
        LinkedList<String>b=new LinkedList<>();
        String x;
        for (int i = 0; i <a ; i++) {
            x=br.readLine();
            if(b.contains(x)){
                b.remove(x);
                b.addFirst(x);
            }
            else{
                b.addFirst(x);
            }
        }
        while(!b.isEmpty())
            out.println(b.pollFirst());

        out.flush();

    }
}


import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.util.*;

public class Main {

    public static void main(String[]args) throws IOException {
        BufferedReader br =new BufferedReader(new InputStreamReader(System.in));
        PrintWriter out =new PrintWriter(System.out);
        int a=Integer.parseInt(br.readLine());
        Deque<String>b=new LinkedList<>();

        String x;
        for (int i = 0; i <a ; i++) {
            x=br.readLine();
            if(b.contains(x)){
                b.remove(x);
                b.addFirst(x);
            }
            else{
                b.addFirst(x);
            }
        }
        while(!b.isEmpty())
            out.println(b.pollFirst());

        out.flush();

    }
}


import java.util.*;
import java.io.*;

public class chatorder {
    public static void main(String[] args) throws Exception{
        Scanner sc = new Scanner(System.in);
        PrintWriter out = new PrintWriter(System.out);
        //sc.waitForInput();
        int n = sc.nextInt();
        HashSet<String> x = new HashSet<>();
        String[] y = new String[n];
        for(int i = 0; i<n; i++){
            y[i] = sc.next();}
        for(int i = n-1; i>=0; i--){
            if(!x.contains(y[i])){
                x.add(y[i]);
                out.println(y[i]);}

            }
        out.flush();

    }

    static class Scanner {
        StringTokenizer st;
        BufferedReader br;

        public Scanner(InputStream system) {
            br = new BufferedReader(new InputStreamReader(system));
        }
        public Scanner(String file) throws Exception {br = new BufferedReader(new FileReader(file));}
        public String next() throws IOException {
            while (st == null || !st.hasMoreTokens()) st = new StringTokenizer(br.readLine());
            return st.nextToken();}
        public String nextLine() throws IOException {return br.readLine(); }
        public int nextInt() throws IOException {return Integer.parseInt(next()); }
        public double nextDouble() throws IOException {return Double.parseDouble(next()); }
        public char nextChar() throws IOException {return next().charAt(0);}
        public Long nextLong() throws IOException {return Long.parseLong(next());}
        public boolean ready() throws IOException {return br.ready();}
        public void waitForInput() throws InterruptedException {Thread.sleep(3000);
        }
    }
}


import java.util.*;
import java.io.*;

public class chatorder {
    public static void main(String[] args) throws Exception{
        Scanner sc = new Scanner(System.in);
        PrintWriter out = new PrintWriter(System.out);
        //sc.waitForInput();
        int n = sc.nextInt();
        ArrayList<String> x = new ArrayList<>(n);
        x.add("");
        for(int i = 0; i<n; i++){
            String temp = sc.next();
            if(x.contains(temp)){
            x.remove(new String (temp));}
            x.add(temp);}
        for(int i = x.size()-1; i>=0; i--){
            System.out.println(x.get(i));}

        //out.flush();

    }

    static class Scanner {
        StringTokenizer st;
        BufferedReader br;

        public Scanner(InputStream system) {
            br = new BufferedReader(new InputStreamReader(system));
        }
        public Scanner(String file) throws Exception {br = new BufferedReader(new FileReader(file));}
        public String next() throws IOException {
            while (st == null || !st.hasMoreTokens()) st = new StringTokenizer(br.readLine());
            return st.nextToken();}
        public String nextLine() throws IOException {return br.readLine(); }
        public int nextInt() throws IOException {return Integer.parseInt(next()); }
        public double nextDouble() throws IOException {return Double.parseDouble(next()); }
        public char nextChar() throws IOException {return next().charAt(0);}
        public Long nextLong() throws IOException {return Long.parseLong(next());}
        public boolean ready() throws IOException {return br.ready();}
        public void waitForInput() throws InterruptedException {Thread.sleep(3000);
        }
    }
}


#include <stdio.h>
struct P
{
	int start,end;
};
int a[1000000];
int visited[100000]={0};
int innum[1000000]={0};
P otrez[1000000];
int notr=0;
int find(int start)
{

	while (!visited[a[start]])
	{
		visited[start]=1;
		start=a[start];
	}
	visited[start]=1;
	return start;
}
void main()
{
	int n;
	scanf("%d",&n);
	for (int i=0;i<n;i++)
	{
		scanf("%d",&a[i]);
		a[i]--;
		innum[a[i]]++;

	}
	for (int i=0;i<n;i++)
		if (innum[i]==0)
		{
			otrez[notr].start=i;
			otrez[notr].end=find(i);
			notr++;

		}

	printf("%d\n",notr);
	for (int i=0;i<notr;i++)
		printf("%d %d\n",otrez[i].end+1,otrez[(i+1)%notr].start+1);

}


#include <stdio.h>
struct P
{
	int start,end;
};
int a[1000000];
int visited[1000000]={0};
int innum[1000000]={0};
P otrez[1000000];
int notr=0;
int find(int start)
{

	while (!visited[a[start]])
	{
		visited[start]=1;
		start=a[start];
	}
	visited[start]=1;
	return start;
}
void main()
{
	int n;
	scanf("%d",&n);
	for (int i=0;i<n;i++)
	{
		scanf("%d",&a[i]);
		a[i]--;
		innum[a[i]]++;

	}
	for (int i=0;i<n;i++)
		if (innum[i]==0)
		{
			otrez[notr].start=i;
			otrez[notr].end=find(i);
			notr++;

		}
	for (int i=0;i<n;i++)
	{
		if (visited[i]==0)
		{
			otrez[notr].start=i;
			otrez[notr].end=find(i);
			notr++;
		}
	}
	printf("%d\n",notr);
	for (int i=0;i<notr;i++)
		printf("%d %d\n",otrez[i].end+1,otrez[(i+1)%notr].start+1);

}


#include <stdio.h>
#include <stack>
#include <math.h>
#include <iostream>
#include <algorithm>
#include <string.h>
#include <string>
#include <set>
#include <memory.h>
#include <vector>
#include <map>
#include <queue>
#include <iomanip>
#include <ctime>
#include <cassert>

#define forn(i, n) for (int i = 0; i < int(n); i++)
#define mp(a, b) make_pair(a, b)
#define sqr(x) ( (x) * (x) )
#define all(a) a.begin(), a.end()

using namespace std;

vector<int> g;
vector<bool> used;

int dfs(int v) {
    used[v] = true;

    int to = g[v];
    if (used[to])
        return v;
    else
        return dfs(to);
}

int main() {

#ifdef _DEBUG
    freopen("input.txt", "r", stdin);
    freopen("output.txt", "w", stdout);
#endif

    int n;
    cin >> n;

    g.resize(n);
    used.resize(n);
    vector<pair<int, int> > ans;
    vector<bool> ok(n);

    forn(i, n) {
        cin >> g[i];
        g[i]--;
        ok[g[i]] = true;
    }

    forn(i, n) {
        if (!used[i] && !ok[i]) {
            ans.push_back(mp(i, dfs(i)));
        }
    }

    forn(i, n) {
        if (!used[i]) {
            ans.push_back(mp(i, dfs(i)));
        }
    }

    if (ans.size() == 1) {
        if (ans[0].first == g[ans[0].second]) {
            cout << 0;
            return 0;
        }
    }

    cout << ans.size() << endl;
    forn(i, ans.size()) {
        cout << ans[i].second + 1 << " " << ans[(i + 1) % ans.size()].first + 1 << endl;
    }

    return 0;
}


#include <cstdio>
#include <cstring>

#include <vector>

using namespace std;

int n;
int g[100000];
int indegree[100000];
bool flag[100000];

vector< pair<int,int> > seq;

void solve( void ){

    for( int i = 0 ; i < n ; i ++ )
        if( indegree[i] == 0 ){

            int begin = i;
            int end = g[i];

            flag[i] = true;
            while( !flag[end] ){
                flag[end] = true;
                end = g[end];
            }

            seq.push_back( make_pair( begin , end ) );
        }

    printf("%d\n",seq.size());
    for( int i = 0 ; i < seq.size() ; i ++ )
        printf("%d %d\n",seq[i].second+1 , seq[(i+1)%seq.size()].first+1 );

    return;
}

int main( void ){

    while( scanf("%d",&n) != EOF ){

        memset( indegree , 0 , sizeof( indegree ) );
        memset( flag , false , sizeof( flag ) );
        seq.clear();

        for( int i = 0 ; i < n ; i ++ ){
            scanf("%d",&g[i]);
            g[i]--;
            indegree[ g[i] ] ++;
        }

        solve();
    }

    return 0;
}


#include <cstdio>
#include <cstring>

#include <vector>

using namespace std;

int n;
int g[100000];
int indegree[100000];
bool flag[100000];

vector< pair<int,int> > seq;

void solve( void ){

    int begining,ending;
    for( int i = 0 ; i < n ; i ++ )
        if( indegree[i] == 0 ){

            begining = i;

            ending = begining;
            while( !flag[ g[ending] ] ){
                flag[ g[ending] ] = true;
                ending = g[ending];
            }

            seq.push_back( make_pair( begining , ending ) );
        }

    if( seq.size() == 0 ){
        printf("%d\n",seq.size());
        return;
    }

    for( int i = 0 ; i < n ; i ++ )
        if( !flag[i] ){

            begining = i;

            ending = begining;
            while( !flag[ g[ending] ] ){
                flag[ g[ending] ] = true;
                ending = g[ending];
            }

            seq.push_back( make_pair( begining , ending ) );
        }
    printf("%d\n",seq.size());

    for( int i = 0 ; i < seq.size() ; i ++ )
        printf("%d %d\n",seq[i].second+1 , seq[(i+1)%seq.size()].first+1 );

    return;
}

int main( void ){

    while( scanf("%d",&n) != EOF ){

        memset( indegree , 0 , sizeof( indegree ) );
        memset( flag , false , sizeof( flag ) );
        seq.clear();

        for( int i = 0 ; i < n ; i ++ ){
            scanf("%d",&g[i]);
            g[i]--;
            indegree[ g[i] ] ++;
        }

        solve();
    }

    return 0;
}


#include <cstdio>
#include <cstring>

#include <vector>

using namespace std;

int n;
int g[100000];
int indegree[100000];
bool flag[100000];

vector< pair<int,int> > seq;

void solve( void ){

    for( int i = 0 ; i < n ; i ++ )
        if( indegree[i] == 0 ){

            int begin = i;
            int end = g[i];

            flag[i] = true;
            while( !flag[end] ){
                flag[end] = true;
                end = g[end];
            }

            seq.push_back( make_pair( begin , end ) );
        }

    if( seq.size() == 0 ){
        printf("%d\n",seq.size());
        return;
    }

    for( int i = 0 ; i < n ; i ++ )
        if( !flag[i] ){

            int begin = i;
            int end = g[i];

            flag[i] = true;
            while( !flag[end] ){
                flag[end] = true;
                end = g[end];
            }

            seq.push_back( make_pair( begin , end ) );
        }
    printf("%d\n",seq.size());

    for( int i = 0 ; i < seq.size() ; i ++ )
        printf("%d %d\n",seq[i].second+1 , seq[(i+1)%seq.size()].first+1 );

    return;
}

int main( void ){

    while( scanf("%d",&n) != EOF ){

        memset( indegree , 0 , sizeof( indegree ) );
        memset( flag , false , sizeof( flag ) );
        seq.clear();

        for( int i = 0 ; i < n ; i ++ ){
            scanf("%d",&g[i]);
            g[i]--;
            indegree[ g[i] ] ++;
        }

        solve();
    }

    return 0;
}


#include <cstdio>
#include <cstring>

#include <vector>

using namespace std;

int n;
int g[100000];
int indegree[100000];
bool flag[100000];

vector< pair<int,int> > seq;

void solve( void ){

    int begining,ending;
    for( int i = 0 ; i < n ; i ++ )
        if( indegree[i] == 0 ){

            begining = i;

            flag[begining] = true;

            ending = begining;
            while( !flag[ g[ending] ] ){
                flag[ g[ending] ] = true;
                ending = g[ending];
            }

            seq.push_back( make_pair( begining , ending ) );
        }

    for( int i = 0 ; i < n ; i ++ )
        if( !flag[i] ){

            begining = i;
            ending = g[i];

            flag[begining] = true;
            while( !flag[ending] ){
                flag[ending] = true;
                ending = g[ending];
            }

            seq.push_back( make_pair( begining , ending ) );
        }

    if( seq.size() == 1 && seq[0].first == seq[0].second ){
        printf("0\n");
        return;
    }

    printf("%d\n",seq.size());

    for( int i = 0 ; i < seq.size() ; i ++ )
        printf("%d %d\n",seq[i].second+1 , seq[(i+1)%seq.size()].first+1 );

    return;
}

int main( void ){

    while( scanf("%d",&n) != EOF ){

        memset( indegree , 0 , sizeof( indegree ) );
        memset( flag , false , sizeof( flag ) );
        seq.clear();

        for( int i = 0 ; i < n ; i ++ ){
            scanf("%d",&g[i]);
            g[i]--;
            indegree[ g[i] ] ++;
        }

        solve();
    }

    return 0;
}


#include <cstdio>
#include <cstring>

#include <vector>

using namespace std;

int n;
int g[100000];
int indegree[100000];
bool flag[100000];

vector< pair<int,int> > seq;

void solve( void ){

    int begining,ending;
    for( int i = 0 ; i < n ; i ++ )
        if( indegree[i] == 0 ){

            begining = i;

            flag[begining] = true;

            ending = begining;
            while( !flag[ g[ending] ] ){
                flag[ g[ending] ] = true;
                ending = g[ending];
            }

            seq.push_back( make_pair( begining , ending ) );
        }

    if( seq.size() == 0 ){
        printf("%d\n",seq.size());
        return;
    }

    for( int i = 0 ; i < n ; i ++ )
        if( !flag[i] ){

            begining = i;

            flag[begining] = true;

            ending = begining;
            while( !flag[ g[ending] ] ){
                flag[ g[ending] ] = true;
                ending = g[ending];
            }

            seq.push_back( make_pair( begining , ending ) );
        }
    printf("%d\n",seq.size());

    for( int i = 0 ; i < seq.size() ; i ++ )
        printf("%d %d\n",seq[i].second+1 , seq[(i+1)%seq.size()].first+1 );

    return;
}

int main( void ){

    while( scanf("%d",&n) != EOF ){

        memset( indegree , 0 , sizeof( indegree ) );
        memset( flag , false , sizeof( flag ) );
        seq.clear();

        for( int i = 0 ; i < n ; i ++ ){
            scanf("%d",&g[i]);
            g[i]--;
            indegree[ g[i] ] ++;
        }

        solve();
    }

    return 0;
}


#include<stdio.h>
#include<string.h>
#include<algorithm>
using namespace std;
#define maxn 111111
#define end asdasd
int in[maxn],g[maxn],vis[maxn], end[maxn];
int l[maxn],r[maxn],ans  = 0;
void dfs(int x)
{
    vis[x] = 1;
    if(vis[g[x]]){
        end[x] = x;
        return;
    }
    dfs(g[x]);
    end[x] = end[g[x]];
}
int main()
{
    int n, i, j, x;
    scanf("%d",&n);
    memset(in,0,sizeof(in));
    memset(vis,0,sizeof(vis));
    for(i=1;i<=n;i++)
    {
        scanf("%d",&x);
        in[x]++;
        g[i] = x;
    }
    for(i=1;i<=n;i++)
    {
        if(in[i]==0&&!vis[i])
        {
            dfs(i);
            l[ans] = i,r[ans] = end[i];
            ans++;
        }
    }
    for(i=1;i<=n;i++)
    {
        if(!vis[i])
        {
            dfs(i);
            l[ans] = i,r[ans] = end[i];
            ans++;
        }
    }
    printf("%d\n",ans);
    if(ans==1&&in[l[0]]>0)
    {
        printf("0\n");
        return 0;
    }
    for(i=0;i<ans-1;i++)
    {
        printf("%d %d\n",r[i],l[i+1]);
    }
    printf("%d %d\n",r[ans-1],l[0]);
    return 0;
}


#include<stdio.h>
#include<string.h>
#include<algorithm>
using namespace std;
#define maxn 111111
int in[maxn],g[maxn],vis[maxn], end[maxn];
int l[maxn],r[maxn],ans  = 0;
void dfs(int x)
{
	vis[x] = 1;
	if(vis[g[x]]){
		end[x] = x;
		return;
	}
	dfs(g[x]);
	end[x] = end[g[x]];
}
int main()
{
    int n, i, j, x;
	scanf("%d",&n);
	memset(in,0,sizeof(in));
	memset(vis,0,sizeof(vis));
	for(i=1;i<=n;i++)
    {
    	scanf("%d",&x);
    	in[x]++;
    	g[i] = x;
    }
    for(i=1;i<=n;i++)
    {
    	if(in[i]==0&&!vis[i])
    	{
	    	dfs(i);
	    	l[ans] = i,r[ans] = end[i];
	    	ans++;
	    }
    }
    for(i=1;i<=n;i++)
    {
    	if(!vis[i])
    	{
	    	dfs(i);
	    	l[ans] = i,r[ans] = end[i];
	    	ans++;
	    }
    }
    printf("%d\n",ans);
    if(ans==1&&in[l[0]]>0)
    {
    	printf("0\n");
    	return 0;
    }
    for(i=0;i<ans-1;i++)
    {
    	printf("%d %d\n",r[i],l[i+1]);
    }
    printf("%d %d\n",r[ans-1],l[0]);
	return 0;
}


#include<stdio.h>
#include<string.h>
#include<algorithm>
using namespace std;
#define maxn 111111
#define end asdasd
int in[maxn],g[maxn],vis[maxn], end[maxn];
int l[maxn],r[maxn],ans  = 0;
void dfs(int x)
{
	vis[x] = 1;
	if(vis[g[x]]){
		end[x] = x;
		return;
	}
	dfs(g[x]);
	end[x] = end[g[x]];
}
int main()
{
    int n, i, j, x;
	scanf("%d",&n);
	memset(in,0,sizeof(in));
	memset(vis,0,sizeof(vis));
	for(i=1;i<=n;i++)
    {
    	scanf("%d",&x);
    	in[x]++;
    	g[i] = x;
    }
    for(i=1;i<=n;i++)
    {
    	if(in[i]==0&&!vis[i])
    	{
	    	dfs(i);
	    	l[ans] = i,r[ans] = end[i];
	    	ans++;
	    }
    }
    for(i=1;i<=n;i++)
    {
    	if(!vis[i])
    	{
	    	dfs(i);
	    	l[ans] = i,r[ans] = end[i];
	    	ans++;
	    }
    }

    if(ans==1&&in[l[0]]>0)
    {
    	printf("0\n");
    	return 0;
    }
      printf("%d\n",ans);
    for(i=0;i<ans-1;i++)
    {
    	printf("%d %d\n",r[i],l[i+1]);
    }
    printf("%d %d\n",r[ans-1],l[0]);
	return 0;
}


#include<stdio.h>
#include<vector>
#include<algorithm>
using namespace std;
#define maxn 111111
int in[maxn],g[maxn],vis[maxn], end[maxn];
int l[maxn],r[maxn],ans  = 0;
void dfs(int x)
{
	vis[x] = 1;
	if(vis[g[x]]){
		end[x] = x;
		return;
	}
	dfs(g[x]);
	end[x] = end[g[x]];
}
int main()
{
    int n, i, j, x;
	scanf("%d",&n);
	memset(in,0,sizeof(in));
	memset(vis,0,sizeof(vis));
	for(i=1;i<=n;i++)
    {
    	scanf("%d",&x);
    	in[x]++;
    	g[i] = x;
    }
    for(i=1;i<=n;i++)
    {
    	if(in[i]==0&&!vis[i])
    	{
	    	dfs(i);
	    	l[ans] = i,r[ans] = end[i];
	    	ans++;
	    }
    }
    for(i=1;i<=n;i++)
    {
    	if(!vis[i])
    	{
	    	dfs(i);
	    	l[ans] = i,r[ans] = end[i];
	    	ans++;
	    }
    }
    printf("%d\n",ans);
    if(ans==1&&in[l[0]]>0)
    {
    	printf("0\n");
    	return 0;
    }
    for(i=0;i<ans-1;i++)
    {
    	printf("%d %d\n",r[i],l[i+1]);
    }
    printf("%d %d\n",r[ans-1],l[0]);
	return 0;
}


// 10 monthes remaining for red =D
#include <stdio.h>
#include <stack>
#include <math.h>
#include <iostream>
#include <algorithm>
#include <string.h>
#include <string>
#include <set>
#include <memory.h>
#include <vector>
#include <map>
#include <queue>
#include <iomanip>
#include <ctime>
#include <cassert>

#define forn(i, n) for (int i = 0; i < int(n); i++)
#define mp(a, b) make_pair(a, b)
#define sqr(x) ( (x) * (x) )
#define all(a) a.begin(), a.end()

using namespace std;

vector<int> g;
vector<bool> used;

int dfs(int v) {
    used[v] = true;

    int to = g[v];
    if (used[to])
        return v;
    else
        return dfs(to);
}

int main() {

#ifdef _DEBUG
    freopen("input.txt", "r", stdin);
    freopen("output.txt", "w", stdout);
#endif

    int n;
    cin >> n;

    g.resize(n);
    used.resize(n);
    vector<pair<int, int> > ans;
    vector<bool> ok(n);

    forn(i, n) {
        cin >> g[i];
        g[i]--;
        ok[g[i]] = true;
    }

    forn(i, n) {
        if (!used[i] && !ok[i]) {
            ans.push_back(mp(i, dfs(i)));
        }
    }

    forn(i, n) {
        if (!used[i]) {
            ans.push_back(mp(i, dfs(i)));
        }
    }

    if (ans.size() == 1) {
        if (ans[0].first == g[ans[0].second]) {
            cout << 0;
            return 0;
        }
    }

    cout << ans.size() << endl;
    forn(i, ans.size()) {
        cout << ans[i].second + 1 << " " << ans[(i + 1) % ans.size()].first + 1 << endl;
    }

    return 0;
}


#define _CRT_SECURE_NO_DEPRECATE

#pragma comment(linker, "/STACK:16777216")

#include <string>
#include <vector>
#include <map>
#include <list>
#include <set>
#include <queue>
#include <iostream>
#include <sstream>
#include <stack>
#include <deque>
#include <cmath>
#include <memory.h>
#include <cstdlib>
#include <cstdio>
#include <cctype>
#include <algorithm>
#include <utility>

using namespace std;

#define FOR(i, a, b) for(int i = a; i < b; ++i)
#define RFOR(i, b, a) for(int i = b - 1; i >= a; --i)
#define REP(i, N) FOR(i, 0, N)
#define RREP(i, N) RFOR(i, N, 0)

#define MIN(A, B) ((A) < (B) ? (A) : (B))
#define MAX(A, B) ((A) > (B) ? (A) : (B))
#define ABS(A) ((A) < 0 ? (-(A)) : (A))
#define ALL(V) V.begin(), V.end()
#define SIZE(V) (int)V.size()
#define pb push_back
#define mp make_pair
#define EPS 1e-7
#define Pi 3.14159265358979

typedef long long Long;
typedef unsigned long long ULong;
typedef unsigned int Uint;
typedef unsigned char Uchar;
typedef vector <int> VI;
typedef pair <int, int> PI;

#define SZ (1 << 17)

int n;

int to[SZ];

int color[SZ];

int comp[SZ];

int cur;

int a[SZ];

int deg[SZ];

int dfs(int x)
{
	if(color[x] == 1)
	{
		comp[x] = cur;
		a[cur] = x;
		++cur;
		return comp[x];
	}
	if(color[x] == 2)
		return comp[x];
	color[x] = 1;
	comp[x] = dfs(to[x]);
	color[x] = 2;
	return comp[x];
}

VI V[SZ];

int main()
{
	scanf("%d", &n);
	REP(i, n)
	{
		scanf("%d", &to[i]);
		--to[i];
		++deg[to[i]];
	}
	REP(i, n)
		if(color[i] == 0)
			dfs(i);
	REP(i, n)
		if(deg[i] == 0)
			V[comp[i]].pb(i);
	vector<PI> R;
	REP(i, cur)
	{
		int ind = (i + 1)%cur;
		REP(j, (int)V[ind].size())
			R.pb(mp(a[i], V[ind][j]));
	}
	printf("%d\n", (int)R.size());
	REP(i, (int)R.size())
		printf("%d %d\n", R[i].first + 1, R[i].second + 1);
	return 0;
}


#define _CRT_SECURE_NO_DEPRECATE

#pragma comment(linker, "/STACK:16777216")

#include <string>
#include <vector>
#include <map>
#include <list>
#include <set>
#include <queue>
#include <iostream>
#include <sstream>
#include <stack>
#include <deque>
#include <cmath>
#include <memory.h>
#include <cstdlib>
#include <cstdio>
#include <cctype>
#include <algorithm>
#include <utility>

using namespace std;

#define FOR(i, a, b) for(int i = a; i < b; ++i)
#define RFOR(i, b, a) for(int i = b - 1; i >= a; --i)
#define REP(i, N) FOR(i, 0, N)
#define RREP(i, N) RFOR(i, N, 0)

#define MIN(A, B) ((A) < (B) ? (A) : (B))
#define MAX(A, B) ((A) > (B) ? (A) : (B))
#define ABS(A) ((A) < 0 ? (-(A)) : (A))
#define ALL(V) V.begin(), V.end()
#define SIZE(V) (int)V.size()
#define pb push_back
#define mp make_pair
#define EPS 1e-7
#define Pi 3.14159265358979

typedef long long Long;
typedef unsigned long long ULong;
typedef unsigned int Uint;
typedef unsigned char Uchar;
typedef vector <int> VI;
typedef pair <int, int> PI;

#define SZ (1 << 17)

int n;

int to[SZ];

int color[SZ];

int comp[SZ];

int cur;

int a[SZ];

int deg[SZ];

int dfs(int x)
{
	if(color[x] == 1)
	{
		comp[x] = cur;
		a[cur] = x;
		++cur;
		return comp[x];
	}
	if(color[x] == 2)
		return comp[x];
	color[x] = 1;
	comp[x] = dfs(to[x]);
	color[x] = 2;
	return comp[x];
}

VI V[SZ];

int main()
{
	scanf("%d", &n);
	REP(i, n)
	{
		scanf("%d", &to[i]);
		--to[i];
		++deg[to[i]];
	}
	REP(i, n)
		if(color[i] == 0)
			dfs(i);
	REP(i, n)
		if(deg[i] == 0)
			V[comp[i]].pb(i);
	if(cur == 1 && V[0].size() == 0)
	{
		puts("0");
		puts("");
		return 0;
	}
	REP(i, cur)
		if(V[i].empty())
			V[i].pb(a[i]);
	vector<PI> R;
	REP(i, cur)
	{
		int ind = (i + 1)%cur;
		REP(j, (int)V[ind].size())
			R.pb(mp(a[i], V[ind][j]));
	}
	printf("%d\n", (int)R.size());
	REP(i, (int)R.size())
		printf("%d %d\n", R[i].first + 1, R[i].second + 1);
	return 0;
}


#define _CRT_SECURE_NO_DEPRECATE

#pragma comment(linker, "/STACK:16777216")

#include <string>
#include <vector>
#include <map>
#include <list>
#include <set>
#include <queue>
#include <iostream>
#include <sstream>
#include <stack>
#include <deque>
#include <cmath>
#include <memory.h>
#include <cstdlib>
#include <cstdio>
#include <cctype>
#include <algorithm>
#include <utility>

using namespace std;

#define FOR(i, a, b) for(int i = a; i < b; ++i)
#define RFOR(i, b, a) for(int i = b - 1; i >= a; --i)
#define REP(i, N) FOR(i, 0, N)
#define RREP(i, N) RFOR(i, N, 0)

#define MIN(A, B) ((A) < (B) ? (A) : (B))
#define MAX(A, B) ((A) > (B) ? (A) : (B))
#define ABS(A) ((A) < 0 ? (-(A)) : (A))
#define ALL(V) V.begin(), V.end()
#define SIZE(V) (int)V.size()
#define pb push_back
#define mp make_pair
#define EPS 1e-7
#define Pi 3.14159265358979

typedef long long Long;
typedef unsigned long long ULong;
typedef unsigned int Uint;
typedef unsigned char Uchar;
typedef vector <int> VI;
typedef pair <int, int> PI;

#define SZ (1 << 17)

int n;

int to[SZ];

int color[SZ];

int comp[SZ];

int cur;

int a[SZ];

int deg[SZ];

int dfs(int x)
{
	if(color[x] == 1)
	{
		comp[x] == cur;
		a[cur] = x;
		++cur;
		return comp[x];
	}
	if(color[x] == 2)
		return comp[x];
	color[x] = 1;
	comp[x] = dfs(to[x]);
	color[x] = 2;
	return comp[x];
}

VI V[SZ];

int main()
{
	scanf("%d", &n);
	REP(i, n)
	{
		scanf("%d", &to[i]);
		--to[i];
		++deg[to[i]];
	}
	REP(i, n)
		if(color[i] == 0)
			dfs(i);
	REP(i, n)
		if(deg[i] == 0)
			V[comp[i]].pb(i);
	vector<PI> R;
	REP(i, cur)
	{
		int ind = (i + 1)%cur;
		REP(j, (int)V[ind].size())
			R.pb(mp(a[i], V[ind][j]));
	}
	printf("%d\n", (int)R.size());
	REP(i, (int)R.size())
		printf("%d %d\n", R[i].first + 1, R[i].second + 1);
	return 0;
}


#include <iostream>
#include <vector>

using namespace std;

int main()
{
	int n;
	cin >> n;
	vector <int> arr(n);
	vector <bool> w(n, false);
	for(int i = 0; i < n; i++)
	{
		cin >> arr[i];
		arr[i]--;
		w[arr[i]] = true;
	}
	vector <int> color(n, 0);
	vector <int> c(n);
	int a = 0, b = -1;
	vector <pair <int, int> > comp;
	for(int i = 0; i < n; i++)
		if(!w[i])
		{
			int index = i;
			while(color[index] == 0)
			{
				color[index] = 1;
				index = arr[index];
			}
			//if(b == -1)
			//	b = index;
			//a++;
			comp.push_back(make_pair(i, index));
			/*int nc = comp.size();
			if(color[index] == 2)
			{
				nc = c[index];
				comp[index].first++;
				continue;
			}
			comp.push_back(make_pair(1, 1));
			index = i;*/
			while(color[index] != 2)
			{
				//c[index] = nc;
				color[index] = 2;
				index = arr[index];
			}
		}
	int cyc = 0;
	for(int i = 0; i < n; i++)
		if(color[i] == -1)
		{
			int index = i;
			while(color[index] == 0)
			{
				color[index] = 2;
				index = arr[index];
			}
			cyc++;
			comp.push_back(make_pair(i, i));
			/*if(color[index] == 2)
				comp.push_back(make_pair(1, 0));
			else
				comp.push_back(make_pair(1, 1));
			index = i;*/
			//while(color[index] != 2)
			//{
			//	color[index] = 2;
			//	index = arr[index];
			//}
		}
	/*int a = 0, b = 0;
	for(int i = 0; i < comp.size(); i++)
	{
		a += comp[i].first;
	}*/
	if(comp.size() == 1 && cyc == 1)
	{
		cout << 0;
		return 0;
	}
	cout << comp.size() << endl;
	for(int i = 1; i < comp.size(); i++)
		cout << comp[i - 1].second + 1 << " " << comp[i].first + 1 << endl;
	cout << comp[comp.size() - 1].second + 1 << " " << comp[0].first + 1 << endl;
	return 0;
}


#include <iostream>
#include <vector>

using namespace std;

int main()
{
	int n;
	cin >> n;
	vector <int> arr(n);
	vector <bool> w(n, false);
	for(int i = 0; i < n; i++)
	{
		cin >> arr[i];
		arr[i]--;
		w[arr[i]] = true;
	}
	vector <int> color(n, 0);
	vector <int> c(n);
	int a = 0, b = -1;
	vector <pair <int, int> > comp;
	for(int i = 0; i < n; i++)
		if(!w[i])
		{
			int index = i;
			while(color[index] == 0)
			{
				color[index] = 2;
				index = arr[index];
			}
			comp.push_back(make_pair(i, index));
		}
	int cyc = 0;
	for(int i = 0; i < n; i++)
		if(color[i] == 0)
		{
			int index = i;
			while(color[index] == 0)
			{
				color[index] = 2;
				index = arr[index];
			}
			cyc++;
			comp.push_back(make_pair(i, i));
		}
	if(comp.size() == 1 && cyc == 1)
	{
		cout << 0;
		return 0;
	}
	cout << comp.size() << endl;
	for(int i = 1; i < comp.size(); i++)
		cout << comp[i - 1].second + 1 << " " << comp[i].first + 1 << endl;
	cout << comp[comp.size() - 1].second + 1 << " " << comp[0].first + 1 << endl;
	return 0;
}


#include <cstdio>
#include <cstring>

#include <algorithm>
#include <vector>

using namespace std;

int n;

int a[100000];

int d[100000];

int w[100000];

vector<pair<int, int> > res;

vector<int> components;

int main()
{
    scanf("%d", &n);

    for(int i = 0; i < n; i++)
    {
    	scanf("%d", &a[i]);
    	a[i]--;

    	d[a[i]]++;
    }

    int cnt = 0;

    for(int i = 0; i < n; i++)
    if (d[i] == 0)
    {
    	cnt++;
    	w[i] = cnt;
    	int v = i;
    	while(1)
    	{
    		v = a[v];
    		if (w[v]) break;
    		w[v] = cnt;
    	}

   	   	if (w[v] == cnt)
   	   	{
   	   		res.push_back(make_pair(v, i));
   	   		components.push_back(i);
   	   	}
   	   	else
   	   	{
   	   		res.push_back(make_pair(v, i));
   	   		int k = i;

   	   		while(w[k] != w[v])
   	   		{
   	   			w[k] = w[v];
   	   			k = a[k];
   	   		}
   	   	}
    }

    int m = components.size();

    if (m > 1)
    for(int i = 0; i < m; i++)
    {
    	int a = components[i];
    	int b = components[(i + 1) % m];

   		res.push_back(make_pair(a, b));
    }

    printf("%d\n", res.size());

    for(int i = 0; i < res.size(); i++) printf("%d %d\n", res[i].first + 1, res[i].second + 1);

	return 0;
}


#include <cstdio>
#include <cstring>

#include <algorithm>
#include <vector>

using namespace std;

int n;

int a[100000];

int d[100000];

int w[100000];

vector<pair<int, int> > res;

vector<int> from, to;

int main()
{
    scanf("%d", &n);

    for(int i = 0; i < n; i++)
    {
    	scanf("%d", &a[i]);
    	a[i]--;

    	d[a[i]]++;
    }

    int cnt = 0;

    for(int i = 0; i < n; i++)
    if (d[i] == 0)
    {
    	cnt++;
    	int v = i;

    	while(!w[v])
    	{
    		w[v] = cnt;
    		v = a[v];
    	}

    	from.push_back(i);
    	  to.push_back(v);
    }

    for(int i = 0; i < n; i++)
    if (!w[i])
    {
    	int v = i;
    	cnt++;
    	while(!w[v])
    	{
    		w[v] = cnt;
    		v = a[v];
    	}

    	from.push_back(i);
    	  to.push_back(v);
    }

    int m = from.size();

    for(int i = 0; i < m; i++)
    {
    	int a = to[i];
    	int b = from[(i + 1) % m];

   		if (a != b) res.push_back(make_pair(a, b));
    }

    printf("%d\n", res.size());

    for(int i = 0; i < res.size(); i++) printf("%d %d\n", res[i].first + 1, res[i].second + 1);

	return 0;
}


#include <cstdio>
#include <cstring>

#include <algorithm>
#include <vector>

using namespace std;

int n;

int a[100000];

int d[100000];

int w[100000];

vector<pair<int, int> > res;

vector<int> components;

int main()
{
    scanf("%d", &n);

    for(int i = 0; i < n; i++)
    {
    	scanf("%d", &a[i]);
    	a[i]--;

    	d[a[i]]++;
    }

    int cnt = 0;

    for(int i = 0; i < n; i++)
    if (d[i] == 0)
    {
    	cnt++;
    	w[i] = cnt;
    	int v = i;
    	while(1)
    	{
    		v = a[v];
    		if (w[v]) break;
    		w[v] = cnt;
    	}

   	   	if (w[v] == cnt)
   	   	{
   	   		res.push_back(make_pair(v, i));
   	   		components.push_back(i);
   	   	}
   	   	else
   	   	{
   	   		res.push_back(make_pair(v, i));
   	   		int k = i;

   	   		while(w[k] != w[v])
   	   		{
   	   			w[k] = w[v];
   	   			k = a[k];
   	   		}
   	   	}
    }

    for(int i = 0; i < n; i++)
    if (!w[i])
    {
  		components.push_back(i);

    	int v = i;
    	cnt++;
    	while(!w[v])
    	{
    		w[v] = cnt;
    		v = a[v];
    	}
    }

    int m = components.size();

    if (m > 1)
    for(int i = 0; i < m; i++)
    {
    	int a = components[i];
    	int b = components[(i + 1) % m];

   		res.push_back(make_pair(a, b));
    }

    printf("%d\n", res.size());

    for(int i = 0; i < res.size(); i++) printf("%d %d\n", res[i].first + 1, res[i].second + 1);

	return 0;
}


#include <iostream>
#include <string>
#include <vector>
#include <algorithm>
#include <queue>
#include <stack>
#include <map>
#include <set>
#include <cmath>
#include <cstdio>

#define forn(i,n) for (int i=0;i<n;i++)
#define ford(i,n) for (int i=n-1;i>=0;i--)
#define mp make_pair
#define pb push_back
#define x first
#define y second
#define pi 3.1415926535897932
#define ll long long

using namespace std;

vector <int> a[101000];
int deg[100100];
vector <pair<int,int>> ans;
bool use[100100],used[100100];

void dfs(int v,int start){
    use[v]=true;
    used[v]=true;
    forn(i,a[v].size())
        if (!use[a[v][i]])
            dfs(a[v][i],start);
        else ans.pb(mp(start,v));
}

void dfs1(int v){
    use[v]=true;
    used[v]=true;
    forn(i,a[v].size())
        if (!use[a[v][i]])
            dfs1(a[v][i]);
}

int main(){
    //freopen ("input.txt","rt",stdin);
    //freopen ("output.txt","wt",stdout);
    int n,t,schet=0;
    memset(deg,0,sizeof(deg));
    memset(use,false,sizeof(use));
    memset(used,false,sizeof(used));
    scanf ("%d", &n);
    forn(i,n){
        scanf ("%d", &t);
        a[i].pb(t-1);
        deg[t-1]++;
    }
    bool q=false;
    forn(i,n)
        if (deg[i]==0){
            dfs(i,i);
            q=true;
            memset(use,false,sizeof(use));
        }
    forn(i,n)
        if (!used[i]){
            dfs1(i);
            ans.pb(mp(i,i));
            memset(use,false,sizeof(use));
        }
    if (!q && ans.size()==1){
        printf ("0");
        exit(0);
    }
    int k=ans.size();
    printf ("%d\n", k);
    forn(i,ans.size())
        printf ("%d %d\n", ans[i].y+1,ans[(i+1) % k].x+1);
    return 0;
}


#define _CRT_SECURE_NO_DEPRECATE

#include <algorithm>
#include <cmath>
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <fstream>
#include <iomanip>
#include <iostream>
#include <limits.h>
#include <list>
#include <map>
#include <set>
#include <string>
#include <time.h>
#include <vector>

#define nextLine() {for(int c=getchar(); c!='\n' && c!=EOF; c=getchar());}
#define sqr(a) ((a)*(a))
#define has(mask,i) (((mask) & (1<<(i))) == 0 ? false : true)
#define eprintf(...) fprintf(stderr, __VA_ARGS__)

#define TASK "file"

using namespace std;

#define pii pair<int,int>
#define mp(x, y) make_pair(x, y)
#define pb(_o_) push_back(_o_)

typedef long long LL;
typedef unsigned long long ULL;
typedef long double ldb;

typedef vector<int> vi;
typedef vector<vi> vvi;
typedef vector<int> vb;
typedef vector<vi> vvb;
typedef list<int> li;
typedef multiset<int>::iterator siit;

const int inf = (1 << 30) - 1;
const ldb eps = 1e-9;
const ldb pi = fabs(atan2(0.0, -1.0));

#ifndef ONLINE_JUDGE
#define parr(a,n,m) for(int i=0;i<n;i++){for(int j=0;j<m;j++)cout<<a[i][j]<<" ";puts("");}puts("");
#else
#define parr(a,n,m) for(int i=0;i<2;i++)i++;
#endif

void ML()
{
    int *ass;
    for (;;)
    {
        ass = new int[2500000];
        for (int i = 0; i < 2500000; i++)
            ass[i] = rand();
    }
}

vvi g;
vvi gr;
int n;
vector<char> was;

void add_edge(const int f, const int t)
{
    g[f].push_back(t);
    gr[t].push_back(f);
}

void LoAd()
{
    cin >> n;
    g.resize(n + 1);
    gr.resize(n + 1);
    for (int t, i = 1; i <= n; i++)
    {
        scanf("%d", &t);
        add_edge(i, t);
    }
}

vi order, component;

void dfs1 (int v)
{
    was[v] = true;
    for (size_t i=0; i<g[v].size(); ++i)
        if (!was[ g[v][i] ])
            dfs1 (g[v][i]);
    order.push_back (v);
}

void dfs2 (int v)
{
    was[v] = true;
    component.push_back(v);
    for (size_t i=0; i<gr[v].size(); ++i)
        if (!was[ gr[v][i] ])
            dfs2 (gr[v][i]);
}

vector<int> hin, hout;
vi numcom;

void SoLvE()
{
    was.assign(n+1, false);
    for (int i = 1; i <= n; i++)
        if (!was[i])
            dfs1 (i);
    was.assign(n+1, false);
    vvi cmps;
    for (int i = 1; i <= n; i++)
    {
        int v = order[n-i];
        if (!was[v])
        {
            dfs2 (v);
            cmps.push_back(component);
            component.clear();
        }
    }
    hin.assign(cmps.size(), false);
    hout.assign(cmps.size(), false);
    numcom.resize(n+1);
    for (int i = 0; i < (int) cmps.size(); i++)
        for (int j = 0; j < (int) cmps[i].size(); j++)
            numcom[ cmps[i][j] ] = i;

    for (int i = 0; i < (int) cmps.size(); i++)
    {
        for (int j = 0; j < (int) cmps[i].size(); j++)
        {
            int v = cmps[i][j];
            for (int k = 0; k < (int) g[v].size(); k++)
                if (numcom[ g[v][k] ] != numcom[v])
                    hout[i] = true;

            for (int k = 0; k < (int) gr[v].size(); k++)
                if (numcom[ gr[v][k] ] != numcom[v])
                    hin[i] = true;
        }
    }

    vector<pii> res;
    vi vin, vout;
    was.clear();
    was.assign(cmps.size(), false);

    for (int i = 1; i <= n; i++)
    {
        int v = numcom[i];
        if (was[v])
            continue;
        was[v] = true;
        if (!hin[v])
            vin.push_back(i);
        if (!hout[v])
            vout.push_back(i);
    }
    int imax = min(vin.size(), vout.size());

    for (int i = 0; i < imax; i++)
        res.push_back(mp(vout[i], vin[i]));
    for (int i = imax; i < (int) vin.size(); i++)
        res.push_back(mp(vout[0], vin[i]));
    for (int i = imax; i < (int) vout.size(); i++)
        res.push_back(mp(vout[i], vin[0]));
    cout << res.size() << endl;
    for (int i = 0; i < (int) res.size(); i++)
        printf("%d %d\n", res[i].first, res[i].second);
}

int main()
{
    srand( (int) time(NULL));
#ifndef ONLINE_JUDGE
    freopen(TASK".in","r",stdin);   freopen(TASK".out","w",stdout);
#endif
    LoAd();
    SoLvE();
    return 0;
}


#define _CRT_SECURE_NO_DEPRECATE

#include <algorithm>
#include <cmath>
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <fstream>
#include <iomanip>
#include <iostream>
#include <limits.h>
#include <list>
#include <map>
#include <set>
#include <string>
#include <time.h>
#include <vector>

#define nextLine() {for(int c=getchar(); c!='\n' && c!=EOF; c=getchar());}
#define sqr(a) ((a)*(a))
#define has(mask,i) (((mask) & (1<<(i))) == 0 ? false : true)
#define eprintf(...) fprintf(stderr, __VA_ARGS__)

#define TASK "file"

using namespace std;

#define pii pair<int,int>
#define mp(x, y) make_pair(x, y)
#define pb(_o_) push_back(_o_)

typedef long long LL;
typedef unsigned long long ULL;
typedef long double ldb;

typedef vector<int> vi;
typedef vector<vi> vvi;
typedef vector<int> vb;
typedef vector<vi> vvb;
typedef list<int> li;
typedef multiset<int>::iterator siit;

const int inf = (1 << 30) - 1;
const ldb eps = 1e-9;
const ldb pi = fabs(atan2(0.0, -1.0));

#ifndef ONLINE_JUDGE
#define parr(a,n,m) for(int i=0;i<n;i++){for(int j=0;j<m;j++)cout<<a[i][j]<<" ";puts("");}puts("");
#else
#define parr(a,n,m) for(int i=0;i<2;i++)i++;
#endif

void ML()
{
    int *ass;
    for (;;)
    {
        ass = new int[2500000];
        for (int i = 0; i < 2500000; i++)
            ass[i] = rand();
    }
}

vvi g;
vvi gr;
int n;
bool was[100500];

void add_edge(const int f, const int t)
{
    g[f].push_back(t);
    gr[t].push_back(f);
}

void LoAd()
{
    cin >> n;
    g.resize(n + 1);
    gr.resize(n + 1);
    for (int t, i = 1; i <= n; i++)
    {
        scanf("%d", &t);
        add_edge(i, t);
    }
}

vector<pii> res;
void dfs(const int v, const int start)
{
    if (v == start)
    {
        if (was[v] || g[v].empty())
            return;
    }

    if (was[v] || g[v].empty())
    {
        was[v] = true;
        res.push_back(mp(v, start));
        add_edge(v, start);
        return;
    }
    was[v] = true;
    dfs(g[v][0], start);
}

void dfs2(const int v)
{
    if (was[v])
        return;
    was[v] = true;
    for (int i = 0; i < (int) g[v].size(); i++)
        dfs2(g[v][i]);
}

void SoLvE()
{
    for (int i = 1; i <= n; i++)
        if (gr[i].empty())
            dfs(i, i);
    memset(was, false, sizeof(was));
    vi cmps;
    for (int i = 1; i <= n; i++)
    {
        if (!was[i])
        {
            cmps.push_back(i);
            dfs2(i);
        }
    }
    if (cmps.size() > 1)
    {
        for (int i = 0; i < (int) cmps.size(); i++)
            res.push_back(mp(cmps[i], cmps[ (i + 1) % cmps.size() ]));
    }
    cout << res.size() << endl;
    for (int i = 0; i < (int) res.size(); i++)
        printf("%d %d\n", res[i].first, res[i].second);
}

int main()
{
    srand( (int) time(NULL));
#ifndef ONLINE_JUDGE
    freopen(TASK".in","r",stdin);   freopen(TASK".out","w",stdout);
#endif
    LoAd();
    SoLvE();
    return 0;
}


#define _CRT_SECURE_NO_DEPRECATE

#include <algorithm>
#include <cmath>
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <fstream>
#include <iomanip>
#include <iostream>
#include <limits.h>
#include <list>
#include <map>
#include <set>
#include <string>
#include <time.h>
#include <vector>

#define nextLine() {for(int c=getchar(); c!='\n' && c!=EOF; c=getchar());}
#define sqr(a) ((a)*(a))
#define has(mask,i) (((mask) & (1<<(i))) == 0 ? false : true)
#define eprintf(...) fprintf(stderr, __VA_ARGS__)

#define TASK "file"

using namespace std;

#define pii pair<int,int>
#define mp(x, y) make_pair(x, y)
#define pb(_o_) push_back(_o_)

typedef long long LL;
typedef unsigned long long ULL;
typedef long double ldb;

typedef vector<int> vi;
typedef vector<vi> vvi;
typedef vector<int> vb;
typedef vector<vi> vvb;
typedef list<int> li;
typedef multiset<int>::iterator siit;

const int inf = (1 << 30) - 1;
const ldb eps = 1e-9;
const ldb pi = fabs(atan2(0.0, -1.0));

#ifndef ONLINE_JUDGE
#define parr(a,n,m) for(int i=0;i<n;i++){for(int j=0;j<m;j++)cout<<a[i][j]<<" ";puts("");}puts("");
#else
#define parr(a,n,m) for(int i=0;i<2;i++)i++;
#endif

void ML()
{
    int *ass;
    for (;;)
    {
        ass = new int[2500000];
        for (int i = 0; i < 2500000; i++)
            ass[i] = rand();
    }
}

vvi g;
vvi gr;
int n;
vector<char> was;

void add_edge(const int f, const int t)
{
    g[f].push_back(t);
    gr[t].push_back(f);
}

void LoAd()
{
    cin >> n;
    g.resize(n + 1);
    gr.resize(n + 1);
    for (int t, i = 1; i <= n; i++)
    {
        scanf("%d", &t);
        add_edge(i, t);
    }
}

vi order, component;

void dfs1 (int v)
{
    was[v] = true;
    for (size_t i=0; i<g[v].size(); ++i)
        if (!was[ g[v][i] ])
            dfs1 (g[v][i]);
    order.push_back (v);
}

void dfs2 (int v)
{
    was[v] = true;
    component.push_back(v);
    for (size_t i=0; i<gr[v].size(); ++i)
        if (!was[ gr[v][i] ])
            dfs2 (gr[v][i]);
}

vector<int> hin, hout;
vi numcom;

void SoLvE()
{
    was.assign(n+1, false);
    for (int i = 1; i <= n; i++)
        if (!was[i])
            dfs1 (i);
    was.assign(n+1, false);
    vvi cmps;
    for (int i = 1; i <= n; i++)
    {
        int v = order[n-i];
        if (!was[v])
        {
            dfs2 (v);
            cmps.push_back(component);
            component.clear();
        }
    }
    hin.assign(cmps.size(), false);
    hout.assign(cmps.size(), false);
    numcom.resize(n+1);
    for (int i = 0; i < (int) cmps.size(); i++)
        for (int j = 0; j < (int) cmps[i].size(); j++)
            numcom[ cmps[i][j] ] = i;

    for (int i = 0; i < (int) cmps.size(); i++)
    {
        for (int j = 0; j < (int) cmps[i].size(); j++)
        {
            int v = cmps[i][j];
            for (int k = 0; k < (int) g[v].size(); k++)
                if (numcom[ g[v][k] ] != numcom[v])
                    hout[i] = true;

            for (int k = 0; k < (int) gr[v].size(); k++)
                if (numcom[ gr[v][k] ] != numcom[v])
                    hin[i] = true;
        }
    }

    vector<pii> res;
    vi vin, vout;
    was.clear();
    was.assign(cmps.size(), false);

    for (int i = 1; i <= n; i++)
    {
        int v = numcom[i];
        if (was[v])
            continue;
        was[v] = true;
        if (!hin[v])
            vin.push_back(i);
        if (!hout[v])
            vout.push_back(i);
    }
    int imax = min(vin.size(), vout.size());

    for (int i = 0; i < imax; i++)
    {
        res.push_back(mp(vout[i], vin[i]));
    }
    for (int i = imax; i < (int) vin.size(); i++)
        res.push_back(mp(vout[0], vin[i]));
    for (int i = imax; i < (int) vout.size(); i++)
        res.push_back(mp(vout[i], vin[0]));
    int cnt = 0;

    for (int i = 0; i < (int) res.size(); i++)
        if (res[i].first != res[i].second)
            cnt++;
    cout << cnt << endl;

    for (int i = 0; i < (int) res.size(); i++)
        if (res[i].first != res[i].second)
        printf("%d %d\n", res[i].first, res[i].second);
}

int main()
{
    srand( (int) time(NULL));
#ifndef ONLINE_JUDGE
    freopen(TASK".in","r",stdin);   freopen(TASK".out","w",stdout);
#endif
    LoAd();
    SoLvE();
    return 0;
}


#define _CRT_SECURE_NO_DEPRECATE

#include <algorithm>
#include <cmath>
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <fstream>
#include <iomanip>
#include <iostream>
#include <limits.h>
#include <list>
#include <map>
#include <set>
#include <string>
#include <time.h>
#include <vector>

#define nextLine() {for(int c=getchar(); c!='\n' && c!=EOF; c=getchar());}
#define sqr(a) ((a)*(a))
#define has(mask,i) (((mask) & (1<<(i))) == 0 ? false : true)
#define eprintf(...) fprintf(stderr, __VA_ARGS__)

#define TASK "file"

using namespace std;

#define pii pair<int,int>
#define mp(x, y) make_pair(x, y)
#define pb(_o_) push_back(_o_)

typedef long long LL;
typedef unsigned long long ULL;
typedef long double ldb;

typedef vector<int> vi;
typedef vector<vi> vvi;
typedef vector<int> vb;
typedef vector<vi> vvb;
typedef list<int> li;
typedef multiset<int>::iterator siit;

const int inf = (1 << 30) - 1;
const ldb eps = 1e-9;
const ldb pi = fabs(atan2(0.0, -1.0));

#ifndef ONLINE_JUDGE
#define parr(a,n,m) for(int i=0;i<n;i++){for(int j=0;j<m;j++)cout<<a[i][j]<<" ";puts("");}puts("");
#else
#define parr(a,n,m) for(int i=0;i<2;i++)i++;
#endif

void ML()
{
    int *ass;
    for (;;)
    {
        ass = new int[2500000];
        for (int i = 0; i < 2500000; i++)
            ass[i] = rand();
    }
}

vvi g;
vvi gr;
int n;
bool was[100500];

void add_edge(const int f, const int t)
{
    g[f].push_back(t);
    gr[t].push_back(f);
}

void LoAd()
{
    cin >> n;
    g.resize(n + 1);
    gr.resize(n + 1);
    for (int t, i = 1; i <= n; i++)
    {
        scanf("%d", &t);
        add_edge(i, t);
    }
}

vector<pii> res;
vector<pii> comps;

void dfs(const int v, const int start)
{
    if (v == start)
    {
        if (was[v] || g[v].empty())
            return;
    }

    if (g[v].empty() || was[ g[v][0]])
    {
        was[v] = true;
        comps.push_back(mp(start, v));
        return;
    }
    was[v] = true;
    dfs(g[v][0], start);
}

void dfs2(const int v)
{
    if (was[v])
        return;
    was[v] = true;
    for (int i = 0; i < (int) g[v].size(); i++)
        dfs2(g[v][i]);
}

void SoLvE()
{
    for (int i = 1; i <= n; i++)
        if (gr[i].empty())
            dfs(i, i);
    for (int i = 1; i <= n; i++)
    {
        if (!was[i])
        {
            comps.push_back(mp(i, i));
            dfs2(i);
        }
    }
    if (comps.size() > 1)
    {
        for (int i = 0; i < (int) comps.size(); i++)
            res.push_back(mp(comps[i].second, comps[ (i + 1) % comps.size() ].first));
    }
    else if (comps.size() == 1)
    {
        if (comps[0].first != comps[0].second)
            res.push_back(mp(comps[0].second, comps[0].first));
    }
    cout << res.size() << endl;
    for (int i = 0; i < (int) res.size(); i++)
        printf("%d %d\n", res[i].first, res[i].second);
}

int main()
{
    srand( (int) time(NULL));
#ifndef ONLINE_JUDGE
    freopen(TASK".in","r",stdin);   freopen(TASK".out","w",stdout);
#endif
    LoAd();
    SoLvE();
    return 0;
}


#define _CRT_SECURE_NO_DEPRECATE

#include <algorithm>
#include <cmath>
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <fstream>
#include <iomanip>
#include <iostream>
#include <limits.h>
#include <list>
#include <map>
#include <set>
#include <string>
#include <time.h>
#include <vector>

#define nextLine() {for(int c=getchar(); c!='\n' && c!=EOF; c=getchar());}
#define sqr(a) ((a)*(a))
#define has(mask,i) (((mask) & (1<<(i))) == 0 ? false : true)
#define eprintf(...) fprintf(stderr, __VA_ARGS__)

#define TASK "file"

using namespace std;

#define pii pair<int,int>
#define mp(x, y) make_pair(x, y)
#define pb(_o_) push_back(_o_)

typedef long long LL;
typedef unsigned long long ULL;
typedef long double ldb;

typedef vector<int> vi;
typedef vector<vi> vvi;
typedef vector<int> vb;
typedef vector<vi> vvb;
typedef list<int> li;
typedef multiset<int>::iterator siit;

const int inf = (1 << 30) - 1;
const ldb eps = 1e-9;
const ldb pi = fabs(atan2(0.0, -1.0));

#ifndef ONLINE_JUDGE
#define parr(a,n,m) for(int i=0;i<n;i++){for(int j=0;j<m;j++)cout<<a[i][j]<<" ";puts("");}puts("");
#else
#define parr(a,n,m) for(int i=0;i<2;i++)i++;
#endif

void ML()
{
    int *ass;
    for (;;)
    {
        ass = new int[2500000];
        for (int i = 0; i < 2500000; i++)
            ass[i] = rand();
    }
}

vvi g;
vvi gr;
int n;
bool was[100500];

void add_edge(const int f, const int t)
{
    g[f].push_back(t);
    gr[t].push_back(f);
}

void LoAd()
{
    cin >> n;
    g.resize(n + 1);
    gr.resize(n + 1);
    for (int t, i = 1; i <= n; i++)
    {
        scanf("%d", &t);
        add_edge(i, t);
    }
}

vector<pii> res;
void dfs(const int v, const int start)
{
    if (v == start)
    {
        if (was[v] || g[v].empty())
            return;
    }

    if (was[v] || g[v].empty())
    {
        was[v] = true;
        res.push_back(mp(v, start));
        add_edge(v, start);
        return;
    }
    was[v] = true;
    dfs(g[v][0], start);
}

void SoLvE()
{
    for (int i = 1; i <= n; i++)
        if (gr[i].empty())
            dfs(i, i);
    memset(was, false, sizeof(was));
    cout << res.size() << endl;
    for (int i = 0; i < (int) res.size(); i++)
        printf("%d %d\n", res[i].first, res[i].second);
}

int main()
{
    srand( (int) time(NULL));
#ifndef ONLINE_JUDGE
    freopen(TASK".in","r",stdin);   freopen(TASK".out","w",stdout);
#endif
    LoAd();
    SoLvE();
    return 0;
}


#define _CRT_SECURE_NO_DEPRECATE

#include <algorithm>
#include <cmath>
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <fstream>
#include <iomanip>
#include <iostream>
#include <limits.h>
#include <list>
#include <map>
#include <set>
#include <string>
#include <time.h>
#include <vector>

#define nextLine() {for(int c=getchar(); c!='\n' && c!=EOF; c=getchar());}
#define sqr(a) ((a)*(a))
#define has(mask,i) (((mask) & (1<<(i))) == 0 ? false : true)
#define eprintf(...) fprintf(stderr, __VA_ARGS__)

#define TASK "file"

using namespace std;

#define pii pair<int,int>
#define mp(x, y) make_pair(x, y)
#define pb(_o_) push_back(_o_)

typedef long long LL;
typedef unsigned long long ULL;
typedef long double ldb;

typedef vector<int> vi;
typedef vector<vi> vvi;
typedef vector<int> vb;
typedef vector<vi> vvb;
typedef list<int> li;
typedef multiset<int>::iterator siit;

const int inf = (1 << 30) - 1;
const ldb eps = 1e-9;
const ldb pi = fabs(atan2(0.0, -1.0));

#ifndef ONLINE_JUDGE
#define parr(a,n,m) for(int i=0;i<n;i++){for(int j=0;j<m;j++)cout<<a[i][j]<<" ";puts("");}puts("");
#else
#define parr(a,n,m) for(int i=0;i<2;i++)i++;
#endif

void ML()
{
    int *ass;
    for (;;)
    {
        ass = new int[2500000];
        for (int i = 0; i < 2500000; i++)
            ass[i] = rand();
    }
}

vvi g;
vvi gr;
int n;
bool was[100500];

void add_edge(const int f, const int t)
{
    g[f].push_back(t);
    gr[t].push_back(f);
}

void LoAd()
{
    cin >> n;
    g.resize(n + 1);
    gr.resize(n + 1);
    for (int t, i = 1; i <= n; i++)
    {
        scanf("%d", &t);
        add_edge(i, t);
    }
}

vector<pii> res;
vector<pii> comps;

void dfs(const int v, const int start)
{
    if (v == start)
    {
        if (was[v] || g[v].empty())
            return;
    }

    if (was[v] || g[v].empty())
    {
        was[v] = true;
        comps.push_back(mp(start, v));
        return;
    }
    was[v] = true;
    dfs(g[v][0], start);
}

void dfs2(const int v)
{
    if (was[v])
        return;
    was[v] = true;
    for (int i = 0; i < (int) g[v].size(); i++)
        dfs2(g[v][i]);
}

void SoLvE()
{
    for (int i = 1; i <= n; i++)
        if (gr[i].empty())
            dfs(i, i);
    for (int i = 1; i <= n; i++)
    {
        if (!was[i])
        {
            comps.push_back(mp(i, i));
            dfs2(i);
        }
    }
    if (comps.size() > 1)
    {
        for (int i = 0; i < (int) comps.size(); i++)
            res.push_back(mp(comps[i].second, comps[ (i + 1) % comps.size() ].first));
    }
    cout << res.size() << endl;
    for (int i = 0; i < (int) res.size(); i++)
        printf("%d %d\n", res[i].first, res[i].second);
}

int main()
{
    srand( (int) time(NULL));
#ifndef ONLINE_JUDGE
    freopen(TASK".in","r",stdin);   freopen(TASK".out","w",stdout);
#endif
    LoAd();
    SoLvE();
    return 0;
}


#include <iostream>
#include <string>
#include <map>
#include <algorithm>
#include <vector>
#include <set>
#include <hash_map>
#include <functional>
#include <sstream>
#include <stack>
#include <iterator>
#include <assert.h>
using namespace std;

const double eps = 1e-10;

int main()
{
	int n = 0;
	cin >> n;
	vector<int> s(n, 0);
	vector<int> in(n, 0);
	for (int i = 0; i < n; i++) {
		cin >> s[i];
		s[i]--;
		in[s[i]]++;
	}

	vector<bool> visited(n, false);
	vector<pair<int, int>> components;
	int a = 0;
	for (int i = 0; i < n; i++) {
		if (visited[i] || in[i] > 0) {
			continue;
		}
		int current = i;
		while (!visited[current]) {
			visited[current] = true;
			current = s[current];
		}
		components.push_back(make_pair(i, current));
		a++;
	}
	int b = 0;
	for (int i = 0; i < n; i++) {
		if (visited[i] || in[i] > 0) {
			continue;
		}
		int current = i;
		while (!visited[current]) {
			visited[current] = true;
			current = s[current];
		}
		components.push_back(make_pair(i, i));
		b++;
	}

	if (a == 0 && b == 1) {
		cout << 0;
		return 0;
	}

	cout << components.size() << endl;
	for (int i = 0; i < components.size(); i++) {
		cout << components[i].second + 1 << " " << components[(i + 1) % components.size()].first + 1 << endl;
	}
	return 0;
}


#include <iostream>
#include <string>
#include <map>
#include <algorithm>
#include <vector>
#include <set>
#include <hash_map>
#include <functional>
#include <sstream>
#include <stack>
#include <iterator>
#include <assert.h>
using namespace std;

const double eps = 1e-10;

int main()
{
	int n = 0;
	cin >> n;
	vector<int> s(n, 0);
	vector<int> in(n, 0);
	for (int i = 0; i < n; i++) {
		cin >> s[i];
		s[i]--;
		in[s[i]]++;
	}

	vector<bool> visited(n, false);
	vector<pair<int, int>> components;
	int a = 0;
	for (int i = 0; i < n; i++) {
		if (visited[i] || in[i] > 0) {
			continue;
		}
		int current = i;
		while (!visited[current]) {
			visited[current] = true;
			current = s[current];
		}
		components.push_back(make_pair(i, current));
		a++;
	}
	int b = 0;
	for (int i = 0; i < n; i++) {
		if (visited[i]) {
			continue;
		}
		int current = i;
		while (!visited[current]) {
			visited[current] = true;
			current = s[current];
		}
		components.push_back(make_pair(i, i));
		b++;
	}

	if (a == 0 && b == 1) {
		cout << 0;
		return 0;
	}

	cout << components.size() << endl;
	for (int i = 0; i < components.size(); i++) {
		cout << components[i].second + 1 << " " << components[(i + 1) % components.size()].first + 1 << endl;
	}
	return 0;
}


#define _USE_MATH_DEFINES
#define _CRT_SECURE_NO_DEPRECATE

#include <algorithm>
#include <cassert>
#include <climits>
#include <cmath>
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <ctime>
#include <deque>
#include <functional>
#include <iostream>
#include <list>
#include <map>
#include <numeric>
#include <queue>
#include <set>
#include <sstream>
#include <stack>
#include <string>
#include <vector>

using namespace std;

#pragma comment(linker, "/STACK:128000000")

template<class T> inline T sqr (T x) {return x * x;}

typedef long long int64;
typedef unsigned long long uint64;
typedef pair<int, int> pii;
typedef pair<int, pii> pip;
typedef pair<pii, int> ppi;
typedef pair<int64, int64> pii64;
typedef pair<double, double> pdd;
typedef pair<string, int> psi;
typedef pair<int, string> pis;
#define eps  1e-8
#define inf  0x7f7f7f7f
#define MP make_pair
#define sfind(S, C) int((S).find(C))
#define sz(C) (int)((C).size())
#define all(C) (C).begin(), (C).end()
#define TASK "test"
#define RR 151

int n;
int g[1 << 17];
char gt[1 << 17];
char used[1 << 17];

int dfs1 (int v) {
    int last = v;
    for (int i = v; !used[i]; i = g[i]) {
        used[i] = true;
        last = i;
    }
    return last;
}

int main() {
#ifndef ONLINE_JUDGE
    freopen(TASK ".in", "r", stdin);
    freopen(TASK ".out", "w", stdout);
#endif

    scanf("%d", &n);
    for (int i = 0, x; i < n; ++i) {
        scanf("%d", &x); --x;
        g[i] = x;
        gt[x] = true;
    }
    vector<pii> comps;
    for (int i = 0; i < n; ++i) {
        if (used[i] || gt[i]) continue;
        int last = dfs1(i);
        comps.push_back(MP(i, last));
    }
    for (int i = 0; i < n; ++i) {
        if (used[i]) continue;
        dfs1(i);
        comps.push_back(MP(i, i));
    }
    vector<pii> ans;
    if (sz(comps) > 1 || comps[0].first != comps[0].second) {
        int m = sz(comps);
        for (int i = 0; i < m; ++i) {
            int x = comps[i].second, y = comps[(i + 1) % m].first;
            ans.push_back(MP(x, y));
        }
    }
    printf("%d\n", sz(ans));
    for (int i = 0; i < sz(ans); ++i)
        printf("%d %d\n", ans[i].first + 1, ans[i].second + 1);

    return 0;
}