Cod sursa(job #1283447)

Utilizator deresurobertoFMI - Deresu Roberto deresuroberto Data 5 decembrie 2014 18:23:17
Problema Lowest Common Ancestor Scor 90
Compilator cpp Status done
Runda Arhiva educationala Marime 1.6 kb
//Deresu Roberto - FMI
//Re :)
#include<fstream>
#include<vector>
#define nx 100007
#define H 300
using namespace std;
int n,m,j,father[nx];
char s[nx*7];

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, int Father)
{
    a[node].height = height;
    father[node] = Father;

    if(!height%H) Father = node;

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

int Lca(int x, int y)
{
    while (father[x]!=father[y])
        if (a[x].height > a[y].height)
            x = father[x];
        else
            y = father[y];

    while(x != y)
        if(a[x].height > a[y].height)
            x=a[x].father;
        else
            y=a[y].father;

    return x;
}

void ReadFather(int &Father)
{
    Father  = 0;

    while(s[j] && s[j]!= ' ') Father = Father*10+s[j]-'0', ++j;
    ++j;
}

void ReadXY(int &x, int &y)
{
    int j;

    fin.getline(s,sizeof(s));

    x = 0;
    y = 0;
    j = 0;

    while(s[j] && s[j]!= ' ') x = x*10+s[j]-'0', ++j;
    ++j;
    while(s[j] && s[j]!= ' ') y = y*10+s[j]-'0', ++j;
}

int main()
{
    fin>>n>>m;
    fin.getline(s,sizeof(s));
    fin.getline(s,sizeof(s));

    for(int i=2;i<=n;i++)
    {
        int Father  = 0;

        ReadFather(Father);

        a[i].father = Father;
        v[Father].push_back(i);
    }

    Dfs(1,1,1);

    for(int i=1;i<=m;i++)
    {
        int x,y;

        ReadXY(x,y);

        fout<<Lca(x,y)<<"\n";
    }

	return 0;
}