Pagini recente » Cod sursa (job #2446751) | Cod sursa (job #1180972) | Cod sursa (job #1684774) | Cod sursa (job #228941) | Cod sursa (job #1998623)
#include <array>
#include <fstream>
#include <queue>
#include <vector>
using namespace std;
const int kMaxAncestors = 30;
struct Node
{
array<int, kMaxAncestors> ancestors;
int ancestor_count = 0;
vector<int> sons;
};
using Tree = vector<Node>;
void Bfs(Tree &t, int node)
{
queue<int> q;
q.push(node);
while (!q.empty()) {
node = q.front();
q.pop();
if (t[node].ancestor_count > 0) {
int ancestor = t[node].ancestors[0];
int order = 0;
while (order < t[ancestor].ancestor_count) {
t[node].ancestors[order + 1] = t[ancestor].ancestors[order];
ancestor = t[node].ancestors.back();
++order;
++t[node].ancestor_count;
}
}
for (int son : t[node].sons) {
q.push(son);
}
}
}
inline int smaller_power(int x)
{
int power = 25;
while ((1 << power) > x) {
--power;
}
return power;
}
int FindAncestor(const Tree &t, int node, int order)
{
int ancestor = node;
while (order > 0 && ancestor != -1) {
int power = smaller_power(order);
if (power >= t[ancestor].ancestor_count) {
ancestor = -1;
} else {
ancestor = t[ancestor].ancestors[power];
order -= (1 << power);
}
}
return ancestor;
}
int main()
{
ifstream fin("stramosi.in");
ofstream fout("stramosi.out");
int nodes, q;
fin >> nodes >> q;
Tree tree(nodes);
for (int i = 0; i < nodes; ++i) {
int father;
fin >> father;
if (father != 0) {
tree[i].ancestors[0] = father - 1;
tree[i].ancestor_count = 1;
tree[father - 1].sons.push_back(i);
}
}
for (int i = 0; i < nodes; ++i) {
if (tree[i].ancestor_count == 0) {
Bfs(tree, i);
}
}
while (q--) {
int node, order;
fin >> node >> order;
fout << FindAncestor(tree, node - 1, order) + 1 << "\n";
}
return 0;
}