天天看點

PAT甲級1052

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 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

#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);
    else
      printf("%05d %d %d\n", v[i].address, v[i].data, v[i].next);

  }
  return 0;
}      
上一篇: PAT甲級1097
下一篇: PAT甲級1056

繼續閱讀