#include <bits/stdc++.h>
using namespace std;
using pii = pair<int, int>;
using vi = vector<int>;
using ll = long long;
int main() {
  ios_base::sync_with_stdio(0);
  cin.tie(0);
  int n;
  cin >> n;
  vi l(n), r(n);
  for (int i = int(0); i < int(n); i++) {
    cin >> l[i] >> r[i];
    l[i]--, r[i]--;
  }
  stack<pii> lists;
  for (int i = int(0); i < int(n); i++) {
    if (l[i] == -1) {
      int start = i, end = i;
      while (r[end] != -1) end = r[end];
      lists.emplace(start, end);
    }
  }
  while (int((lists).size()) >= 2) {
    auto [start1, end1] = lists.top();
    lists.pop();
    auto [start2, end2] = lists.top();
    lists.pop();
    r[end1] = start2;
    l[start2] = end1;
    lists.emplace(start1, end2);
  }
  for (int i = int(0); i < int(n); i++)
    cout << l[i] + 1 << ' ' << r[i] + 1 << '\n';
  return 0;
}
