模拟题,注意当k == 1 与 k == n时情况
#include <stdio.h>
#include <string.h>
#include <iostream>
#include <algorithm>
#include <map>
using namespace std;
const int N = 100005;
struct Node
{
int pre;
int value;
int lat;
}node[N];
int order[N];
int size;
map<int, int> pre2idx;
void solve1(int fir, int n)
{
map<int, int>::iterator it = pre2idx.find(fir);
order[size++] = it->second;
while (node[it->second].lat != -1)
{
it = pre2idx.find(node[it->second].lat);
order[size++] = it->second;
}
}
void solve2(int k, int n)
{
int bound = n / k * k;
int idx = k;
while (idx <= bound)
{
int boundt = idx;
int boundb = idx - k + 1;
while (boundt >= boundb)
{
int next = 0;
if (boundt > boundb) next = boundt - 1;
else
{
if (idx < bound)
next = idx + k;
else if (idx == bound)
{
if (bound < n)
next = idx + 1;
else if (bound == n)
{
printf("%05d %d -1
", node[order[boundt]].pre, node[order[boundt]].value);
break;
}
}
}
printf("%05d %d %05d
", node[order[boundt]].pre, node[order[boundt]].value, node[order[next]].pre);
boundt--;
}
idx += k;
}
bound++;
while (bound <= n)
{
if (node[order[bound]].lat != -1)
printf("%05d %d %05d
", node[order[bound]].pre, node[order[bound]].value, node[order[bound]].lat);
else printf("%05d %d -1
", node[order[bound]].pre, node[order[bound]].value);
bound++;
}
}
int main()
{
int fir, n, k;
while (scanf("%d%d%d", &fir, &n, &k) != EOF)
{
pre2idx.clear(); size = 1;
for (int i = 0; i < n; i++)
{
scanf("%d%d%d", &node[i].pre, &node[i].value, &node[i].lat);
pre2idx.insert(make_pair(node[i].pre, i));
}
solve1(fir, n);
solve2(k , size - 1);
}
return 0;
}
/*
00100 6 6
00000 4 99999
00100 1 -1
68237 6 -1
33218 3 00000
99999 5 68237
12309 2 33218
*/