Pagini recente » Cod sursa (job #2284563) | Cod sursa (job #1840118) | Cod sursa (job #1716406) | Cod sursa (job #3204001) | Cod sursa (job #1998600)
#include <fstream>
#include <vector>
using namespace std;
struct Node
{
vector<int> sons;
vector<int> ancestors;
};
using Tree = vector<Node>;
void Dfs(Tree &t, int node)
{
if (!t[node].ancestors.empty()) {
int ancestor = t[node].ancestors[0];
int order = 0;
while (order < (int)t[ancestor].ancestors.size()) {
t[node].ancestors.push_back(t[ancestor].ancestors[order]);
ancestor = t[node].ancestors.back();
++order;
}
}
for (int son : t[node].sons) {
Dfs(t, 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 >= (int)t[ancestor].ancestors.size()) {
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.push_back(father - 1);
tree[father - 1].sons.push_back(i);
}
}
for (int i = 0; i < nodes; ++i) {
if (tree[i].ancestors.empty()) {
Dfs(tree, i);
}
}
while (q--) {
int node, order;
fin >> node >> order;
fout << FindAncestor(tree, node - 1, order) + 1 << "\n";
}
return 0;
}