求助
#include<bits/stdc++.h>
using namespace std;
struct yy{
int sf=0;
int gs=0;
queue <int> ck1;
queue <int> ck;
};
int n[100005];
yy m[100005];
void f(int bh){
if(m[bh].sf==1){
return ;
}
if(m[bh].gs==0){
m[bh].sf=1;
cout<<bh<<" ";
return ;
}
m[bh].sf=1;
cout<<bh<<" ";
for(int i=1;i<=m[bh].gs;i++){
f(m[bh].ck.front());
m[bh].ck.push(m[bh].ck.front());
m[bh].ck.pop();
}
return ;
}
void f2(int bh){
if(m[bh].sf==1){
return ;
}
if(m[bh].gs==0){
m[bh].sf=1;
return ;
}
m[bh].sf=1;
for(int i=1;i<=m[bh].gs;i++){
if(m[m[bh].ck.front()].sf==0){
cout<<m[bh].ck.front()<<" ";
}
m[bh].ck.push(m[bh].ck.front());
m[bh].ck.pop();
}
for(int i=1;i<=m[bh].gs;i++){
f2(m[bh].ck.front());
m[bh].ck.push(m[bh].ck.front());
m[bh].ck.pop();
}
return ;
}
int main(){
int a,b;
cin>>a>>b;
int c,d;
for(int i=1;i<=b;i++){
cin>>c>>d;
m[c].gs++;
m[c].ck1.push(d);
}
for(int i=1;i<=a;i++){
if(m[i].gs!=0){
int cgs=0;
for(int j=1;j<=m[i].gs;j++){
cgs++;
n[cgs]=m[i].ck1.front();
m[i].ck1.push(m[i].ck1.front());
m[i].ck1.pop();
}
sort(n+1,n+1+m[i].gs);
for(int j=1;j<=m[i].gs;j++){
m[i].ck.push(n[j]);
}
}
}
f(1);
cout<<endl;
cout<<1<<" ";
for(int i=1;i<=a;i++){
m[i].sf=0;
}
f2(1);
return 0;
}