

#include<cstdio>
#include<vector>
#include<cstring>
#include<algorithm>
using namespace std;
const int N=110;
int pre[N],nex[N];
int z[N],y[N];
int wan[N];
int fa[N];
int findx(int x)
{
return fa[x]=(x==fa[x]?x:findx(fa[x]));
}
int main()
{
int n;
scanf("%d",&n);
int tot1=0,tot2=0,tot3=0;
for(int i=0; i<=n; ++i) fa[i]=i;
for(int i=1; i<=n; ++i)
{
scanf("%d%d",&pre[i],&nex[i]);
int x1=findx(i),x2=findx(pre[i]),x3=findx(nex[i]);
if(x1!=x2&&x2!=0) fa[x2]=x1;
if(x1!=x3&&x3!=0) fa[x3]=x1;
if(pre[i]==0&&nex[i]==0)
{
wan[tot2++]=i;
continue;
}
if(pre[i]==0) z[tot1++]=i;
if(nex[i]==0) y[tot3++]=i;
}
bool used[120];
memset(used,0,sizeof(used));
for(int i=0; i<tot1-1; ++i)
{
int f1=findx(y[i]);
for(int j=0; j<tot1; ++j)
{
int f2=findx(z[j]);
if(f1!=f2&&!used[z[j]])
{
used[z[j]]=1;
fa[f2]=f1;
pre[z[j]]=y[i];
nex[y[i]]=z[j];
break;
}
}
}
int last,qi;
if(tot2==n) last=1,qi=1;
else last=y[tot1-1],qi=0;
for(; qi<tot2; ++qi)
{
nex[last]=wan[qi];
pre[wan[qi]]=last;
last=wan[qi];
}
for(int i=1; i<=n; ++i)
printf("%d %d\n",pre[i],nex[i]);
}
/*10
0 9
4 0
5 0
7 2
0 3
8 10
0 4
0 6
1 0
6 0*/