#define _CRT_SECURE_NO_WARNINGS
#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;
struct Node
{
int addr, key, next;
}node[100000];
vector<Node> listNode;
bool cmp(const Node &a, const Node &b)
{
return a.key < b.key;
}
int main()
{
// freopen("in.txt", "r", stdin);
int n, start;
cin >> n >> start;
if (start == -1)
{
cout << "0 -1" << endl;
return 0;
}
int Address, Key, Next;
for (int i = 0; i < n; i++)
{
cin >> Address >> Key >> Next;
node[Address].addr = Address;
node[Address].key = Key;
node[Address].next = Next;
}
int cnt = 0;
int cur = start;
do
{
cnt++;
listNode.push_back(node[cur]);
cur = node[cur].next;
} while (cur != -1);
sort(listNode.begin(), listNode.end(), cmp);
printf("%d %05d\n", cnt, listNode[0].addr);
for (int i = 0; i < cnt - 1; i++)
printf("%05d %d %05d\n", listNode[i].addr, listNode[i].key, listNode[i + 1].addr);
printf("%05d %d -1\n", listNode[cnt - 1].addr, listNode[cnt - 1].key);
return 0;
}
再贴一个之前的代码,不知道为什么有几个测试点不能过。留此存照。以后再来仔细看看。
#define _CRT_SECURE_NO_WARNINGS
#include <iostream>
#include <string>
using namespace std;
struct Node
{
int key, next;
}node[100005];
int main()
{
freopen("in.txt", "r", stdin);
int n, start;
cin >> n >> start;
if (start == -1)
{
cout << "0 -1" << endl;
return 0;
}
int Address, Key, Next;
for (int i = 0; i < n; i++)
{
scanf("%d %d %d", &Address, &Key, &Next);
// cin >> Address >> Key >> Next;
node[Address].key = Key;
node[Address].next = Next;
}
int cur = start;
int next = node[cur].next;
int cnt = 0;
while (cur != -1)
{
cnt++;
if (node[cur].key < node[next].key)
{
cur = next;
next = node[cur].next;
}
else
{
node[cur].next = node[next].next;
if (node[start].key > node[next].key)
{
node[next].next = start;
start = next;
}
else
{
int pos = start;
while (node[next].key > node[node[pos].next].key)
pos = node[pos].next;
node[next].next = node[pos].next;
node[pos].next = next;
}
cur = node[cur].next;
next = node[cur].next;
}
}
printf("%d %05d\n", cnt, start);
do
{
printf((node[start].next != -1 ? "%05d %d %05d\n" : "%05d %d %d\n"), start, node[start].key, node[start].next);
start = node[start].next;
} while (start != -1);
return 0;
}