1052 Linked List Sorting (25分)
作者:CHEN, Yue
单位:浙江大学
代码长度限制:16 KB
时间限制:400 ms
内存限制:64 MB
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 (<10^5) 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 [−10^5 ,10^5], 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:
5 00001
11111 100 -1
00001 0 22222
33333 100000 11111
12345 -1 33333
22222 1000 12345
Sample Output:
5 12345
12345 -1 00001
00001 0 11111
11111 100 22222
22222 1000 33333
33333 100000 -1
题意
提供N个和首个结点的地址值,其中结点包括所在地址(address)、值(key)和指向地址(next),输出所给结点形成的链表长度,再根据结点值的大小升序重新输出结点。
思路
与题A1032相似,由于地址值较小,可以构建静态链表,从首地址开始遍历链表并计数,排序可以用sort函数,自定义cmp。结点引入一个判断值flag,用来判断结点是否属于链表,要把它排序在前面的。
参考代码
#include <iostream>
#include <algorithm>
using namespace std;
struct Node{
int address,next,key;
bool flag;
}node[100010];
bool cmp(Node a,Node b){
if(!a.flag||!b.flag) return a.flag>b.flag;
else return a.key<b.key;
}
int main()
{
int n,st,cnt=0;
scanf("%d%d",&n,&st);
for(int i=0;i<n;i++){
int ad;
scanf("%d",&ad);
scanf("%d%d",&node[ad].key,&node[ad].next);
node[ad].address=ad;
}
while(st!=-1){
node[st].flag=1;
st=node[st].next;
cnt++;
}
sort(node,node+100010,cmp);
if(cnt!=0){
printf("%d %05d\n",cnt,node[0].address);
for(int i=0;i<cnt-1;i++){
printf("%05d %d %05d\n",node[i].address,node[i].key,node[i+1].address);
}
printf("%05d %d -1\n",node[cnt-1].address,node[cnt-1].key);
}else printf("0 -1\n");
return 0;
}
若有错误,欢迎指正