分块先分块输出再讨论输出每块最后一个点,看这个点是否在最后一块内。
#include<vector>
#include<iostream>
#include<algorithm>
#include<unordered_map>
#include<set>
#include<map>
#include<cstring>
#include<string>
#include<queue>
#include<array>
#include<stack>
using namespace std;
const int maxn = 100010;
struct Node
{
int address,data,next;
bool flag;
int order;
}node[maxn];
bool cmp(Node a, Node b)
{
return a.order < b.order;
}
int main()
{
for (int i = 0; i < maxn; i++)
{
node[i].order = maxn;
}
int begin, n, k;
cin >> begin >> n >> k;
int address, data, next;
for (int i = 0; i < n; i++)
{
cin >> address >> data >> next;
node[address].address = address;
node[address].next = next;
node[address].data = data;
}
int p = begin, count = 0;
while (p != -1)
{
node[p].order = count++;
p = node[p].next;
}
sort(node, node + maxn, cmp);
n = count;
for (int i = 0; i < n / k; i++)
{
for (int j = (i + 1) * k - 1; j > i* k; j--)
{
printf("%05d %d %05d\n", node[j].address, node[j].data, node[j - 1].address);
}
//讨论每一块最后一个点
printf("%05d %d ", node[i * k].address, node[i * k].data);
if (i < n / k - 1)
{
printf("%05d\n", node[(i + 2) * k - 1].address);
}
else
{
if (n % k == 0)
cout << "-1" << endl;
else
{
printf("%5d\n", node[(i + 1) * k].address);
for (int i = n / k * k; i < n; i++)
{
printf("%05d %d ", node[i].address, node[i].data);
if (i < n - 1)
{
printf("%05d\n", node[i].next);
}
else
{
printf("-1\n");
}
}
}
}
}
}
#include<iostream>
#include<algorithm>
using namespace std;
const int maxn = 1000001;
struct Node
{
int address, data, next;
int order;
}node[maxn];
bool cmp(Node a, Node b)
{
return a.order < b.order;
}
int main()
{
for (int i = 0; i < maxn; i++)
{
node[i].order = maxn;
}
int begin, n, k;
cin >> begin >> n >> k;
int address, data, next;
for (int i = 0; i < n; i++)
{
cin >> address >> data >> next;
node[address].address = address;
node[address].data = data;
node[address].next = next;
}
int p = begin, count = 0;
while (p != -1)
{
node[p].order = count++;
p = node[p].next;
}
n = count;//顺应题意
sort(node, node + maxn, cmp);
for (int i = 0; i <n/k; i++)
{
for (int j = (i + 1) * k - 1; j > i* k; j--)
{
printf("%05d %d %05d\n", node[j].address, node[j].data, node[j - 1].address);
}
printf("%05d %d ", node[i * k].address, node[i * k].data);
if (i < n/k - 1)
{
printf("%05d\n", node[(i + 2) * k - 1].address);
}
else
{
if (n % k == 0)
cout << "-1" << endl;
else
{
printf("%05d\n", node[(i + 1) * k].address);
for (int q = (i + 1) * k; q < n; q++)
{
printf("%05d %d ", node[q].address, node[q].data);
if (q < n - 1)
{
printf("%05d\n", node[q].next);
}
else
{
printf("-1\n");
}
}
}
}
}
}