#include <bits/stdc++.h>
using namespace std;
const long long oo = 0x3f3f3f3f3f3f3f3f;
const double eps = 1e-9;
int main() {
  ios_base::sync_with_stdio(false);
  cin.tie(NULL);
  long long n;
  cin >> n;
  vector<long long> l(n), r(n);
  for (long long i = (0); i < (n); i++) cin >> l[i] >> r[i], l[i]--, r[i]--;
  vector<long long> c(n, -1);
  long long C = 0;
  for (long long i = (0); i < (n); i++)
    if (c[i] == -1) {
      c[i] = C;
      for (long long j = l[i]; j != -1; j = l[j]) c[j] = C;
      for (long long j = r[i]; j != -1; j = r[j]) c[j] = C;
      C++;
    }
  for (long long i = (0); i < (n); i++)
    if (r[i] == -1)
      for (long long j = (0); j < (n); j++)
        if (l[j] == -1)
          if (c[i] == c[j] + 1) r[i] = j, l[j] = i;
  for (long long i = (0); i < (n); i++)
    cout << l[i] + 1 << " " << r[i] + 1 << endl;
}
