Cod sursa(job #1075237)

Utilizator impulseBagu Alexandru impulse Data 8 ianuarie 2014 19:25:01
Problema Lowest Common Ancestor Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 1.54 kb
//
//  main.c
//  lca
//
//  Created by Alexandru Bâgu on 1/8/14.
//  Copyright (c) 2014 Alexandru Bâgu. All rights reserved.
//

#include <stdio.h>
#include <stdlib.h>
typedef struct pItem
{
    int v;
    struct pItem *next;
} item;

void add(item* p, int v)
{
    while(p->next != NULL)
        p = p->next;
    p->v = v;
    p->next = (item*)malloc(sizeof(item));
    p->next->next = NULL;
}

#define maxn 100005

item C[maxn];
int n, q, T[maxn], T2[maxn], LEV[maxn];
const int lev_reset = 200;


void dfs(int nod, int n1, int lev)
{
    LEV[nod] = lev;
    T2[nod] = n1;
    
    if(lev % lev_reset == 0) n1 = nod;
    
    item* i = C + nod;
    while(i->next != NULL)
    {
        dfs(i->v, n1, lev+1);
        i = i->next;
    }
}

int lca(int x, int y)
{
    while(T2[x] != T2[y])
        if(LEV[x] > LEV[y])
            x = T2[x];
        else
            y = T2[y];
    
    while(x != y)
        if(LEV[x] > LEV[y])
            x = T[x];
        else
            y = T[y];
    
    return x;
}

void read()
{
    scanf("%d %d", &n, &q);
    int i;
    for(i = 0; i < maxn; i++)
    {
        C[i].v = 0;
        C[i].next = NULL;
        T[i] = 0;
    }
    for(i = 2; i <= n; i++)
    {
        scanf("%d", T + i);
        add(&C[T[i]], i);
    }
    dfs(1, 0, 0);
}

void solve()
{
    int x, y;
    while(q-- > 0)
    {
        scanf("%d %d", &x, &y);
        printf("%d\n", lca(x,y));
    }
}

int main(int argc, const char * argv[])
{
    freopen("lca.in", "r", stdin);
    freopen("lca.out", "w", stdout);
    
    read();
    solve();
    return 0;
}