PAT 1133

题目 : Splitting A Linked List

分值 : 25
难度 : 中等题
思路 : 自定义链表 + 按要求排序
坑点 : 在用order时,更改之后的值再放入排序数组,不要先放入再更改

具体代码如下

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
#include <iostream>
#include <algorithm>
using namespace std ;
typedef struct Node
{
int address;
int self ;
int next ;
int flag = 0 ;
int order=0 ;
}Nodes;
Nodes list[100001] ;
Nodes temp[100001] ;
bool cmp(Node a ,Node b)
{
if(a.flag == b.flag)
return a.order < b.order ;
else
return a.flag < b.flag ;

}
int main() {
int S , N ,K;
cin >> S >> N >> K ;
for(int i = 0 ; i< N ;i++)
{
int addr , value ,next ;
cin >> addr >> value >>next ;
list[addr].address = addr ;
list[addr].self = value ;
list[addr].next = next ;
if(value < 0)
list[addr].flag = 1 ;
else if(value >=0 && value <= K)
list[addr].flag = 2 ;
else if(value > K)
list[addr].flag =3 ;
}
int cur =S ;
int count = 0 ;
while(cur != -1 )
{
list[cur].order = count;
temp[count++] = list[cur] ;
cur = list[cur].next ;
}
sort(temp,temp+count,cmp) ;
for(int i= 0 ; i< count ; i++)
{
if(i)
printf("%05d\n",temp[i].address ) ;
printf("%05d %d ",temp[i].address,temp[i].self ) ;
}
cout <<"-1"<<endl ;

}