Cod sursa(job #1500857)

Utilizator bciobanuBogdan Ciobanu bciobanu Data 12 octombrie 2015 19:27:00
Problema Lowest Common Ancestor Scor 0
Compilator cpp Status done
Runda Arhiva educationala Marime 2.09 kb
#include <cstdio>

using namespace std;

const int Nmax = 1e5;
const int Mmax = 2e4;
const int NIL = -1;

struct List {
    int v, next;
};

List l[Nmax];
int adj[Nmax];
int ptr;

List Q[2 * Mmax];
int q[Nmax];

int father[Nmax], height[Nmax];
int ancestor[Nmax], answer[Mmax];
bool color[Nmax];

void inline addEdge(int u, int v) {
    l[ptr].v = v;
    l[ptr].next = adj[u];
    adj[u] = ptr++;
}

void inline addQuery(int u, int v, int pos) {
    Q[pos].v = v;
    Q[pos].next = q[u];
    q[u] = pos;
}

int inline getFather(int x) {
    int r = x;

    while (father[r] != r) {
        r = father[r];
    }
    while (father[x] != x) {
        int y = father[x];
        father[x] = r;
        x = y;
    }
    return r;
}

void inline UnionSet(int x, int y) {
    x = getFather(x);
    y = getFather(y);
    if (height[x] > height[y]) {
        father[y] = x;
    } else if (height[y] > height[x]) {
        father[x] = y;
    } else {
        father[y] = x;
        height[x]++;
    }
}

void DFS(int u) {
    father[u] = u;
    ancestor[u] = u;
    for (int i = adj[u]; i != NIL; i = l[i].next) {
        int v = l[i].v;
        DFS(v);
        UnionSet(u, v);
        ancestor[getFather(u)] = u;
    }
    color[u] = 1;
    for (int i = q[u]; i != NIL; i = Q[i].next) {
        int v = Q[i].v;
        if (color[v]) {
            answer[i >> 1] = ancestor[getFather(v)];
        }
    }
}

int main(void) {
    freopen("stramosi.in", "r", stdin);
    freopen("stramosi.out", "w", stdout);
    int n, m;
    int u, v;

    scanf("%d%d", &n, &m);
    for (int i = 0; i < n; i++) {
        adj[i] = NIL;
        q[i] = NIL;
    }
    for (int i = 1; i < n; i++) {
        scanf("%d", &u);
        addEdge(u - 1, i);
    }
    for (int i = 0; i < m; i++) {
        scanf("%d%d", &u, &v);
        u--; v--;
        addQuery(u, v, 2 * i);
        addQuery(v, u, 2 * i + 1);
    }
    fclose(stdin);

    DFS(0);

    for (int i = 0; i < m; i++) {
        printf("%d\n", answer[i] + 1);
    }
    fclose(stdout);
    return 0;
}