题目:https://pintia.cn/problem-sets/994805342720868352/problems/994805425780670464

这题本来看了解题模版以后觉得很简单,但还是有一些地方要注意。

  1. flag用来标记结点,虽然模版里没说,但感觉必用,用了会很方便 不是必用,在题目给定的是一定同属于一个链表的结点时不需要flag
  2. flag的true要在遍历初始化key的时候置
  3. cmp比较函数的编写,一般是两级,通过flag将不在链里面的都放到后面去
  4. 格式化输出%05d的时候需要特殊处理-1
  5. 这题的输出很神奇,我一开始都没反应过来,它实际上并没有修改结点的next,而是单纯将结点后面一个结点的地址输出了而已,我也是服了

代码

  1. #include<vector>
  2. #include<algorithm>
  3. #include<iostream>
  4. using namespace std;
  5. const int maxn = 100010;
  6. struct Node{
  7. int address, key, next;
  8. bool flag;
  9. }node[maxn];
  10. bool cmp(Node a, Node b){
  11. if(a.flag == false || b.flag == false) return a.flag > b.flag;
  12. else return a.key < b.key;
  13. }
  14. int main(){
  15. for(int i = 0; i < maxn; i++){
  16. node[i].flag = false;
  17. }
  18. int n, s1;
  19. scanf("%d%d", &n, &s1);
  20. int address, key, next;
  21. for(int i = 0; i < n; i++){
  22. scanf("%d%d%d", &address, &key, &next);
  23. node[address].key = key;
  24. node[address].next = next;
  25. node[address].address = address;
  26. }
  27. int p = s1, count = 0;
  28. while(p != -1){
  29. node[p].flag = true;
  30. count++;
  31. p = node[p].next;
  32. }
  33. sort(node, node + maxn, cmp);
  34. if(count == 0){
  35. printf("0 -1\n");
  36. return 0;
  37. }
  38. printf("%d %05d\n", count, node[0].address);
  39. for(int i = 0; i < count; i++){
  40. if(i != count -1) printf("%05d %d %05d\n", node[i].address, node[i].key, node[i+1].address);
  41. else printf("%05d %d -1\n", node[i].address, node[i].key);
  42. }
  43. return 0;
  44. }