1052 Linked List Sorting (25 分)
此题注意先从头节点跑一遍链表存起来, 因为可能有很多空链。
#include <iostream>
#include <algorithm>
#include <vector>
using namespace std;
struct node{
int s1, value, s2;
}a[101000];
vector<node> v;
bool cmp(node x, node y){
return x.value < y.value;
}
int main(){
int n, k, x, y, z, ret = 0;
cin >> n >> k;
for(int i = 0; i < n; ++i){
cin >> x >> y >> z;
a[x] = {x, y, z};
}
for(int i = k; i != -1; i = a[i].s2){
v.push_back(a[i]);
ret++;
}
if(ret == 0)
cout << "0 -1" ;
else{
sort(v.begin(), v.end(), cmp);
printf("%d %05d\n", ret, v[0].s1);
for(int i = 0; i < ret; ++i){
printf("%05d %d ", v[i].s1, v[i].value);
if(i == ret - 1)
printf("-1\n");
else
printf("%05d\n", v[i + 1].s1);
}
}
}