满分C++:
#include <iostream>
#include <vector>
#include <string>
#include <map>
#include <cmath>
#include <algorithm>
using namespace std;
struct node
{
int add, next_add;
int content;
};
int main()
{
int add, N, K;
map<int, node> info_map;
cin>>add>>N>>K;
for(int i = 0; i < N; i++){
node n;
scanf("%d %d %d", &(n.add), &(n.content), &(n.next_add));
info_map[n.add] = n;
}
vector<node> result;
while(add >= 0){
result.push_back(info_map[add]);
add = info_map[add].next_add;
}
for(int i = 0; i + K <= result.size(); i += K){
reverse(&(result[i]), &(result[i + K]));
}
for(auto itr = result.begin(); itr != result.end(); itr ++){
if (itr!= result.begin())
printf(" %05d\n", itr -> add);
printf("%05d %d", itr -> add, itr -> content);
}
printf(" -1\n");
}
超时lua:
local readFunc = io.read('*a'):gmatch('%p?%w+')
local info_table = {}
local first_node = readFunc() N = readFunc() K = tonumber(readFunc())
for i = 1, N do
local node = {add = readFunc(), content = readFunc(), next_node = readFunc()}
info_table[node.add] = node
end
local stack = {}
local result_array = {}
while first_node ~= "-1" do
table.insert(stack, 1, info_table[first_node])
first_node = info_table[first_node].next_node
if #stack >= K then
for _, node in pairs(stack) do
table.insert(result_array, node)
end
stack = {}
end
end
for index, node in pairs(result_array) do
print(node.add .. " " .. node.content .. " " .. (result_array[index + 1] and result_array[index + 1].add or (stack[#stack] and stack[#stack].add or "-1")))
end
for index = #stack, 1, -1 do
node = stack[index]
print(node.add .. " " .. node.content .. " " .. node.next_node)
end