Pagini recente » Cod sursa (job #1211382) | Cod sursa (job #175762) | Istoria paginii runda/nustiucesazic | Cod sursa (job #520530) | Cod sursa (job #2882140)
#include<iostream>
#include<fstream>
#include<vector>
using namespace std;
ifstream f("stramosi.in");
ofstream g("stramosi.out");
int n,m;
int LOG;
int v[250005];
int up[250005][18];
int x,y;
void Citire()
{
f>>n>>m;
for(int i=1;i<=n;i++)
{
f>>v[i];
}
}
void BuildMatrix()
{
v[1] = 0;
for(int i=1;i <= n ;i++)
{
up[i][1] = v[i];
for(int j=2;j<=LOG;j++)
{
up[i][j] = up[up[i][j-1]][j-1];
}
}
}
int KthAncestor(int node)
{
if(y == 0)
return node;
LOG = 0;
while(1<<LOG<=y)
{
LOG++;
}
y=y-LOG;
KthAncestor(up[node][LOG]);
}
int main()
{
Citire();
while(1<<LOG<=n)
LOG++;
BuildMatrix();
for(int i=1;i<=m;i++)
{
f>>x>>y;
g<<KthAncestor(x)<<"\n";
}
}