#include <bits/stdc++.h>
using namespace std;
const signed long long int INF = 1e9;
vector<int> l, r;
vector<bool> us;
pair<int, int> dfs(int x) {
  int Gl(x), Gr(x);
  us[x] = 1;
  while (1) {
    us[Gr] = 1;
    if (r[Gr] == 0) break;
    Gr = r[Gr];
  }
  while (1) {
    us[Gl] = 1;
    if (l[Gl] == 0) break;
    Gl = l[Gl];
  }
  return make_pair(Gl, Gr);
}
bool solve() {
  int n;
  cin >> n;
  l.resize(n + 1);
  r.resize(n + 1);
  us.resize(n + 1);
  vector<int> L, R;
  for (int i(1); i <= n; i++) {
    scanf("%d %d", &l[i], &r[i]);
    if (l[i] == 0) L.push_back(i);
    if (r[i] == 0) R.push_back(i);
  }
  vector<pair<int, int> > sec;
  for (int i(1); i <= n; i++) {
    if (!us[i]) {
      sec.push_back(dfs(i));
    }
  }
  for (int i(1); i < sec.size(); i++) {
    r[sec[i - 1].second] = sec[i].first;
    l[sec[i].first] = sec[i - 1].second;
  }
  for (int i(1); i <= n; i++) {
    printf("%d %d\n", l[i], r[i]);
  }
  return 1;
}
int main() {
  solve();
  return 0;
}
