import java.util.Scanner;
import java.util.Random;
import java.io.PrintWriter;

public class shuffle {
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        PrintWriter writer = new PrintWriter(System.out);

        int n = scanner.nextInt();

        Random random = new Random(n * 54213);

        int[] left = new int[n];
        int[] right = new int[n];

        for (int i = 0; i < n; ++i) {
            left[i] = scanner.nextInt() - 1;
            right[i] = scanner.nextInt() - 1;
        }

        int[] oldToNew = new int[n];
        int[] newToOld = new int[n];

        for (int i = 0; i < n; ++i)
            oldToNew[i] = i;

        for (int i = 0; i < n; ++i) {
            int j = i + random.nextInt(n - i);

            if (i != j) {
                int t = oldToNew[i];
                oldToNew[i] = oldToNew[j];
                oldToNew[j] = t;
            }
        }

        for (int i = 0; i < n; ++i)
            newToOld[oldToNew[i]] = i;

        writer.println(n);

        for (int i = 0; i < n; ++i) {
            int old = newToOld[i];
            int l;
            int r;

            if (left[old] >= 0)
                l = oldToNew[left[old]];
            else
                l = -1;

            if (right[old] >= 0)
                r = oldToNew[right[old]];
            else
                r = -1;

            writer.println((l + 1) + " " + (r + 1));
        }

        writer.close();
    }
}
