代码
#include<bits/stdc++.h>
using namespace std;
const int N = 2e6+10;
int a[N],b[N],c[N],res[N],cnt[N],k[N],o[N];
struct hh
{
int l,r;
}h[N];
int main()
{
int n,m,j = 0, t = 0; scanf("%d %d",&n,&m);
for(int i=1;i<=m;i++)
{
int x,y,z; scanf("%d %d %d",&x,&y,&z);
h[x].l = y ,h[x].r = z;
}
int re = n;
for(int i=1;i<=m;i++)
{
if(a[abs(h[re].l)] == 0){
res[j] = re;
cnt[j] = h[re].l;
j ++;
a[abs(h[re].l)] ++;
}else{
k[t] = re;
o[t] = h[re].l;
t ++;
}
re = h[re].r;
if(re == -1) break;
}
for(int i=0;i<j;i++)
{
if(i != j-1) printf("%05d %d %05d\n",res[i],cnt[i],res[i+1]);
else printf("%05d %d -1\n",res[i],cnt[i]);
}
for(int i=0;i<t;i++)
{
if(i != t-1) printf("%05d %d %05d\n",k[i],o[i],k[i+1]);
else printf("%05d %d -1\n",k[i],o[i]);
}
return 0;
}