Cod sursa(job #1283399)

Utilizator deresurobertoFMI - Deresu Roberto deresuroberto Data 5 decembrie 2014 17:20:09
Problema Lowest Common Ancestor Scor 90
Compilator cpp Status done
Runda Arhiva educationala Marime 0.92 kb
//Deresu Roberto - FMI
//Re :)
#include<fstream>
#include<vector>
#define nx 100007
using namespace std;
int n,m,x,y,father;

struct lca
{
    int father;
    int height;
}a[nx];

vector<int>v[nx];
ifstream fin("lca.in");
ofstream fout("lca.out");

void dfs(int node, int height)
{
    a[node].height = height;

    for(int i=0;i<v[node].size();i++)
        dfs(v[node][i], height+1);
}

int lca(int x,int y)
{
    while(a[x].height > a[y].height) x = a[x].father;
    while(a[y].height > a[x].height) y = a[y].father;

    while(x != y)
    {
        x = a[x].father;
        y = a[y].father;
    }

    return x;
}

int main()
{
    fin>>n>>m;

    for(int i=2;i<=n;i++)
    {
        fin>>father;
        a[i].father = father;
        v[father].push_back(i);
    }

    dfs(1,1);

    for(int i=1;i<=m;i++)
    {
        fin>>x>>y;
        fout<<lca(x,y)<<"\n";
    }

	return 0;
}