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

诶嘿嘿,自己写出来了,没有使用算法笔记的方法,而且感觉自己的方法更简单,其实就是用了一个vector数组,本来一开始想用queue的,后来发现好像没有必要了,而且没有数组方便,

  1. 唯一一个注意点,sort的范围是maxn,不要在validcount中排序

代码

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