#include <bits/stdc++.h>
using namespace std;
const int maxn = int(1e5) + 5;
int l[maxn], r[maxn], P[maxn], sz[maxn];
inline int root(int x) { return (x == P[x]) ? x : (P[x] = root(P[x])); }
void dsu(int x, int y) {
  x = root(x), y = root(y);
  if (sz[x] < sz[y]) swap(x, y);
  P[y] = x;
  sz[x] += sz[y];
}
int main(void) {
  int n;
  scanf("%d", &n);
  set<int> strt, en;
  for (int i = 1; i <= n; i++) P[i] = i, sz[i] = -1;
  for (int i = 1; i <= n; i++) {
    scanf("%d%d", &l[i], &r[i]);
    if (!l[i])
      strt.insert(i);
    else
      dsu(i, l[i]);
    if (!r[i])
      en.insert(i);
    else
      dsu(i, r[i]);
  }
  while (int(strt.size()) > 1 && int(en.size()) > 1) {
    int x = *strt.begin(), y;
    for (auto it : en) {
      if (root(it) != root(x)) {
        y = it;
        break;
      }
    }
    en.erase(y), strt.erase(x);
    r[y] = x, l[x] = y;
    dsu(y, r[y]), dsu(x, l[x]);
  }
  for (int i = 1; i <= n; i++) printf("%d %d\n", l[i], r[i]);
}
