PAT甲级1052

来源:互联网 发布:阿里云 安卓软件 编辑:程序博客网 时间:2024/05/18 01:34

1052. Linked List Sorting (25)

时间限制
400 ms
内存限制
65536 kB
代码长度限制
16000 B
判题程序
Standard
作者
CHEN, Yue

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:
5 0000111111 100 -100001 0 2222233333 100000 1111112345 -1 3333322222 1000 12345
Sample Output:
5 1234512345 -1 0000100001 0 1111111111 100 2222222222 1000 3333333333 100000 -1

#include<cstdio>#include<vector>#include<algorithm>using namespace std;const int MAXN = 100000;struct Node{int address, data,next;Node():address(-1),data(100001),next(-1){}bool operator<(Node n){return data < n.data;}}node[MAXN];int main(){int N, start;scanf("%d%d", &N, &start);vector<Node> v; int address;for (int i = 0; i < N; i++){scanf("%d", &address);node[address].address = address;scanf("%d %d", &node[address].data, &node[address].next);}if (node[start].data == 100001||start==-1)//必须判断开始节点地址是不是为NULL,否则最后一个点过不了{printf("0 -1");//特判,所给节点全无效return 0;}int s = start;while (s != -1){v.push_back(node[s]);s = node[s].next;}//只存有效节点,也就是从开始位置能够遍历出来的节点,这判断无效节点是个坑,题目一点提示都不给sort(v.begin(), v.end());start = v[0].address;for (int i = 0; i < v.size()-1; i++){v[i].next = v[i + 1].address;}v[v.size()-1].next = -1;printf("%d %05d\n", v.size(), start);for (int i = 0; i < v.size(); i++){if(v[i].next!=-1)printf("%05d %d %05d\n", v[i].address, v[i].data, v[i].next);elseprintf("%05d %d %d\n", v[i].address, v[i].data, v[i].next);}return 0;}

0 0
原创粉丝点击