Cod sursa(job #1283871)

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

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

vector<int>v[nx];
deque<int>q;

ifstream fin("lca.in");
ofstream fout("lca.out");

void Bfs()
{
    q.push_back(1);
    q.push_back(1);
    q.push_back(1);

    while(!q.empty())
    {
        int node  = q.front();
            q.pop_front();
        int Father = q.front();
            q.pop_front();
        int height = q.front();
            q.pop_front();

        a[node].height = height;
        father[node] = Father;

        if(height%H == 0) Father = node;

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

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, int &j)
{
    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));

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

        ReadFather(Father,j);

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

    Bfs();

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

        ReadXY(x,y);

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

    return 0;
}