#include <bits/stdc++.h>
using namespace std;
const int N = 500001;
int n, l[N], r[N], dsu[N];
int find(int u) { return dsu[u] == u ? u : dsu[u] = find(dsu[u]); }
int main() {
  cin >> n;
  for (int i = 1; i <= n; ++i) dsu[i] = i;
  for (int i = 1; i <= n; ++i) {
    cin >> l[i] >> r[i];
    if (l[i]) dsu[find(i)] = find(l[i]);
    if (r[i]) dsu[find(i)] = find(r[i]);
  }
  for (int i = 1; i <= 2 * n; ++i) {
    for (int j = 1; j <= n; ++j) {
      for (int k = 1; k <= n; ++k) {
        if (k == j) continue;
        if (r[j] == 0 && l[k] == 0 && find(j) != find(k)) {
          l[k] = j;
          r[j] = k;
          dsu[find(k)] = find(j);
        }
      }
    }
  }
  for (int i = 1; i <= n; ++i) {
    printf("%d %d\n", l[i], r[i]);
  }
  return 0;
}
