Pagini recente » Cod sursa (job #2370827) | Istoria paginii runda/bbbba/clasament | Cod sursa (job #1467867) | Cod sursa (job #1315599) | Cod sursa (job #1556460)
//Lowest Common Ancestor
//Complexitate : Memorie O(n) , Timp O(n*m);
#include <cstdio>
#include <vector>
#include <fstream>
#define nmax 100005
using namespace std;
int n,m,t[nmax],g[nmax];
vector <int> v[nmax];
void dfs(int x)
{
int i;
for (i=0;i<v[x].size();i++) {
g[v[x][i]]=g[x]+1;
dfs(v[x][i]);
}
}
class instream {
public:
instream() {}
instream(const char *file_name) {
input_file=fopen(file_name,"r");
cursor=0;
fread(buffer,SIZE,1,input_file);
}
inline instream &operator >>(int &n) {
while((buffer[cursor]<'0'||buffer[cursor]>'9')&&buffer[cursor]!='-') {
advance();
}
n=0;
while('0'<=buffer[cursor]&&buffer[cursor]<='9') {
n=n*10+buffer[cursor]-'0';
advance();
}
return *this;
}
private:
FILE *input_file;
static const int SIZE=1<<15;
int cursor;
char buffer[SIZE];
inline void advance() {
++ cursor;
if(cursor==SIZE) {
cursor=0;
fread(buffer,SIZE,1,input_file);
}
}
};
instream f("lca.in");
ofstream fout("lca.out");
int main()
{
int i,j,a,b;
f>>n>>m;
for (i=2;i<=n;i++) {
f>>t[i];
v[t[i]].push_back(i);
}
dfs(1);
for (i=1;i<=m;i++) {
f>>a>>b;
while (a!=b) {
if (g[a]>g[b])
a=t[a];
else
b=t[b];
}
fout<<a<<'\n';
}
return 0;
}