PAT K block链表反转
满分
/**
题意: 每k位反转链表
*/
#include <iostream>
#include <cstring>
#include <vector>
#include <algorithm>
using namespace std;
const int N = 100010;
int p[N], w[N];
int main()
{
int m, n, k;
cin >> m >> n >> k;
while (n --)
{
int a, b, c;
scanf("%d %d %d", &a, &c, &b);
p[a] = b;
w[a] = c;
}
int cnt = 0;
vector<int> res;
for(int i = m; i != -1; i = p[i])
{
res.push_back(i);
}
int size = res.size() % k; // 这一步必须思考清晰,取余则是多余数据
// size / k 则是你有几个block
reverse(res.begin(), res.end());
bool flag = true;
for(int i = 0; i < res.size(); )
{
if (flag) reverse(res.begin() + i, res.begin() + i + size), i += size, flag = false;
else {
reverse(res.begin() + i, res.begin() + i + k);
i += k;
}
}
for(int i = 0; i < res.size(); i++)
{
printf("%05d %d ", res[i], w[res[i]]);
if (i != res.size() - 1) printf("%05d\n", res[i + 1]);
else printf("-1\n");
}
}
满分
#include <iostream>
#include <cstring>
#include <vector>
#include <algorithm>
using namespace std;
const int N = 100010;
int h[N], w[N];
int main()
{
int s, n, k;
cin >> s >> n >> k;
while (n --)
{
int a, b, c;
cin >> a >> c >> b;
h[a] = b;
w[a] = c;
}
vector<int> res;
for(int i = s; i != - 1; i = h[i])
{
res.push_back(i);
}
reverse(res.begin(), res.end());
int last = res.size() % k;
int len = res.size() / k;
reverse(res.begin(), res.begin() + last);
int pos = last;
while (len --)
{
reverse(res.begin() + pos, res.begin() + pos + k);
pos += k;
}
for(int i = 0; i <res.size(); i++)
{
printf("%05d %d ", res[i], w[res[i]]);
if (i == res.size() - 1) printf("-1\n");
else printf("%05d\n", res[i + 1]);
}
}