Pagini recente » Diferente pentru pregatire-online-pentru-bacalaureatul-la-informatica intre reviziile 5 si 4 | Diferente pentru pregatire-online-pentru-bacalaureatul-la-informatica intre reviziile 3 si 4 | Monitorul de evaluare | Cod sursa (job #3361874)
#include <fstream>
#include <vector>
using namespace std;
ifstream cin("stramosi.in");
ofstream cout("stramosi.out");
int n, m;
struct Node {
int depth;
int idx;
Node *parent;
Node *jump;
};
vector<Node*> all_nodes;
void make_leaf(Node *parent, int idx) {
Node *leaf = new Node();
all_nodes.push_back(leaf);
leaf->idx = idx;
leaf->parent = parent;
leaf->depth = parent->depth + 1;
Node *jump = parent->jump;
if (parent->depth - jump->depth == jump->depth - jump->jump->depth)
leaf->jump = jump->jump;
else
leaf->jump = parent;
}
void make_root(int idx) {
Node *root = new Node();
all_nodes.push_back(root);
root->idx = idx;
root->parent = nullptr;
root->depth = 0;
root->jump = root;
}
void exit() {
for (auto pointer : all_nodes) delete pointer;
all_nodes.clear();
}
int find_anc(Node* node, int depth) {
int real_depth = node->depth - depth;
if (real_depth < 0) return 0;
while (node->depth > real_depth) {
if (node->jump->depth < real_depth) {
node = node->parent;
} else {
node = node->jump;
}
}
return node->idx + 1;
}
int main() {
cin >> n >> m;
for (int node_idx = 0 ; node_idx < n ; ++node_idx) {
int parent; cin >> parent;
if (parent == 0) make_root(node_idx);
else make_leaf(all_nodes[parent - 1], node_idx);
}
for (int i = 1 ; i <= m ; ++i) {
int node; cin >> node; --node;
int query_depth; cin >> query_depth;
cout << find_anc(all_nodes[node], query_depth) << "\n";
}
exit();
return 0;
}