思路
纯模拟,测试点3过不了的原因是,可能有多个next为-1的结点,而只有一个是单链表上的,其他的都是多余的,解决这个坑点即可
AC代码
#include<bits/stdc++.h>
#define rep(i,x,y) for(int i=x; i<=y; ++i)
#define per(i,x,y) for(int i=x; i>=y; --i)
#define pushk push_back
#define popk pop_back
#define mem(a,b) memset(a,b,sizeof a)
#define PII pair<int,int>
#define ll long long
using namespace std;
const int N = 1e5+9;
unordered_map<int,int> to,from,Date;
struct node{
int ad,da,ne;
};
int main() {
int ad,s,n,e,cnt=0;
cin>>s>>n;
rep(i,1,n){
int ad,da,ne;
cin>>ad>>da>>ne;
to[ad]=ne;
Date[ad]=da;
from[ne]=ad;
if(ne==-1) cnt++;
}
int m=0;
n=0;
vector<node> ve;
e=s;
while(to[e]!=-1) e=to[e],m++,n++;
m++,n++;
from[-1]=e;
// cout<<n<<" "<<m<<'\n';
while(m){
ve.pushk({e,Date[e], to[e]}),m--;
if(s!=e) ve.pushk({s,Date[s],to[s]}),m--;
e=from[e];
s=to[s];
}
ve.pushk({-1,0,-1});
rep(i,0,n-1){
printf("%05d %d ",ve[i].ad,ve[i].da);
if(i==n-1) puts("-1");
else{
printf("%05d\n",ve[i+1].ad);
}
}
return 0;
}
/*
99999 4
99999 5 00100
00100 10 -1
00000 10 -1
09900 9 -1
00100 5
00000 4 99999
00100 1 12309
33218 3 00000
99999 5 -1
12309 2 33218
*/