1052. Linked List Sorting (25)

- 日理万妓 2022-05-31 13:56 248阅读 0赞

A linked list consists of a series of structures, which are not necessarily adjacent in memory. We assume that each structure contains an integer key and a Next pointer to the next structure. Now given a linked list, you are supposed to sort the structures according to their key values in increasing order.

Input Specification:

Each input file contains one test case. For each case, the first line contains a positive N (< 105) and an address of the head node, where N is the total number of nodes in memory and the address of a node is a 5-digit positive integer. NULL is represented by -1.

Then N lines follow, each describes a node in the format:

Address Key Next

where Address is the address of the node in memory, Key is an integer in [-105, 105], and Next is the address of the next node. It is guaranteed that all the keys are distinct and there is no cycle in the linked list starting from the head node.

Output Specification:

For each test case, the output format is the same as that of the input, where N is the total number of nodes in the list and all the nodes must be sorted order.

Sample Input:

  1. 5 00001
  2. 11111 100 -1
  3. 00001 0 22222
  4. 33333 100000 11111
  5. 12345 -1 33333
  6. 22222 1000 12345

Sample Output:

  1. 5 12345
  2. 12345 -1 00001
  3. 00001 0 11111
  4. 11111 100 22222
  5. 22222 1000 33333
  6. 33333 100000 -1

题目大意:

代码:

  1. #include<stdio.h>
  2. #include<algorithm>
  3. using namespace std;
  4. struct node
  5. {
  6. int index;
  7. int key;
  8. int next;
  9. int flag;
  10. }arr[100000];
  11. bool cmp(struct node a,struct node b)
  12. {
  13. if(a.flag!=b.flag)
  14. return a.flag>b.flag;
  15. return a.key<b.key;
  16. }
  17. int main()
  18. {
  19. int i,j,n,m,k,t,l,num;
  20. scanf("%d %d",&n,&m);
  21. for(i=0;i<n;i++)
  22. {
  23. scanf("%d %d %d",&k,&t,&l);
  24. arr[k].index=k;
  25. arr[k].key=t;
  26. arr[k].next=l;
  27. }
  28. l=0;
  29. num=0;
  30. for(i=m;i!=-1;i=arr[i].next)
  31. {
  32. num++;
  33. arr[i].flag=1;
  34. }
  35. if(num==0)
  36. {
  37. printf("0 -1\n");
  38. return 0;
  39. }
  40. sort(arr,arr+100000,cmp);
  41. printf("%d %05d\n",num,arr[0].index);
  42. for(i=0;i<num;i++)
  43. {
  44. if(i+1<num)
  45. {
  46. printf("%05d %d %05d\n",arr[i].index,arr[i].key,arr[i+1].index);
  47. }
  48. else
  49. {
  50. printf("%05d %d %d\n",arr[i].index,arr[i].key,-1);
  51. }
  52. }
  53. return 0;
  54. }

发表评论

表情:
评论列表 (有 0 条评论,248人围观)

还没有评论,来说两句吧...

相关阅读