-
Notifications
You must be signed in to change notification settings - Fork 0
/
1052.cpp
116 lines (98 loc) · 1.65 KB
/
1052.cpp
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
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
#include <stdio.h>
#include <algorithm>
using namespace std;
typedef struct node
{
int addr;
int key;
int next;
int flag;
}node;
node records[100005];
int N;
int results[100005];
bool less_than_node(const node &A, const node &B)
{
return A.addr < B.addr;
}
bool less_than_key(const node &A, const node &B)
{
if (1 == A.flag && 0 == B.flag)
{
return true;
}
if (0 == A.flag && 1 == B.flag)
{
return false;
}
if (1 == A.flag && 1 == B.flag)
{
return A.key < B.key;
}
return A.addr < B.addr;
}
int binary_search_node(int target)
{
int low = 0;
int high = N-1;
int mid;
while (low <= high)
{
mid = (high+low)/2;
if (records[mid].addr == target)
{
return mid;
}
if (records[mid].addr < target)
{
low = mid + 1;
}
else
{
high = mid - 1;
}
}
return -1;
}
int main()
{
int address;
int length = 0;
int index;
scanf("%d", &N);
scanf("%d", &address);
for (int i = 0; i != N; ++i)
{
scanf("%d", &records[i].addr);
scanf("%d", &records[i].key);
scanf("%d", &records[i].next);
}
sort(records, records+N, less_than_node);
while(address != -1)
{
index = binary_search_node(address);
// ²éÕÒ²»³É¹¦
if (index == -1)
{
break;
}
records[index].flag = 1;
address = records[index].next;
++length;
}
// ×îºóÒ»¸öcase
if (0 == length)
{
printf("%d -1\n", length);
return 0;
}
sort(records, records+N, less_than_key);
printf("%d %05d\n", length, records[0].addr);
for (int i = 0; i != length-1; ++i)
{
printf("%05d %d %05d\n", records[i].addr, records[i].key, records[i+1].addr);
}
printf("%05d %d -1\n", records[length-1].addr, records[length-1].key);
system("pause");
return 0;
}