/**
  * Reads in a sequence of pairs of integers (between 0 and N-1) from standard input, where each
  * integer represents some object; if the objects are in different components, merge the two
  * components and print the pair to standard output.
  */
 public static void main(String[] args) {
   int N = StdIn.readInt();
   WeightedQuickUnionUF uf = new WeightedQuickUnionUF(N);
   while (!StdIn.isEmpty()) {
     int p = StdIn.readInt();
     int q = StdIn.readInt();
     if (uf.connected(p, q)) continue;
     uf.union(p, q);
     StdOut.println(p + " " + q);
   }
   StdOut.println(uf.count() + " components");
 }
  public static void main(String[] args) {
    int N = StdIn.readInt();
    WeightedQuickUnionUF uf = new WeightedQuickUnionUF(N);

    // read in a sequence of pairs of integers (each in the range 0 to N-1),
    // calling find() for each pair: If the members of the pair are not already
    // call union() and print the pair.
    while (!StdIn.isEmpty()) {
      int p = StdIn.readInt();
      int q = StdIn.readInt();
      if (uf.connected(p, q)) continue;
      uf.union(p, q);
      StdOut.println(p + " " + q);
    }
    StdOut.println("# components: " + uf.count());
  }