Note :In some testcase,some nodes may not in the list ! So we can’t think the number of nodes in the list is N!Only can use -1 as the flag of the end of list.
#include <iostream>
#include <stdio.h>
#include<stdlib.h>
#include <math.h>
#include <algorithm>
#include <vector>
#include <map>
#include <string>
#include<stack>
#include <unordered_map>
#include <queue>
using namespace std;
unordered_map<int, int> Value;
unordered_map<int, int> Next;
unordered_map<int, int> List;
int main() {
int af, N, K;
cin >> af >> N >> K;
int a1, v, a2;
for (int i = 0; i < N; i++)
{
scanf("%d%d%d",&a1,&v,&a2);
Value[a1] = v;
Next[a1] = a2;
}
int n=-1, l=-1, m=-1; //当前各class的末尾地址
int fn=-1, fl=-1, fm=-1; //各class的首地址
int a = af;
while(a!=-1)
{
if (Value[a] < 0) {
if (fn == -1) {
fn = a;
n = a;
}
else {
List[n] = a;
n = a;
}
}
else if (Value[a] >= 0 && Value[a] <= K)
{
if (fl == -1) {
fl = a;
l = a;
}
else {
List[l] = a;
l = a;
}
}
else {
if (fm == -1) {
fm = a;
m = a;
}
else {
List[m] = a;
m = a;
}
}
a = Next[a];
}
if (n != -1) {//有负值
af = fn;
if (l != -1) { List[n] = fl; List[l] = fm; List[m]=-1; }//有小于k的值
else {List[n] = fm;List[m]=-1;}
}
else if (l != -1) { af = fl; List[l] = fm;List[m]=-1; }//无负值
else {af = fm; List[m]=-1;}
a = af;
while(1)
{
printf("%05d %d ", a, Value[a]);
if(List[a]!=-1){
printf("%05d\n", List[a]);
a=List[a];
}
else {printf("-1\n");
break;
}
}
return 0;
}