Cod sursa(job #3230116)

Utilizator Tudor06MusatTudor Tudor06 Data 19 mai 2024 12:08:38
Problema Lowest Common Ancestor Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 2.61 kb
#include <bits/stdc++.h>

using namespace std;

const int BUFSIZE = ( 1 << 16 );

class InParser {
private:
	FILE *fin;
	char *buff;
	int sp;

	char read_ch() {
		++sp;
		if (sp == BUFSIZE) {
			sp = 0;
			fread(buff, 1, BUFSIZE, fin);
		}
		return buff[sp];
	}

public:
	InParser(const char* nume) {
		fin = fopen(nume, "r");
		buff = new char[BUFSIZE]();
		sp = BUFSIZE - 1;
	}
	
	InParser& operator >> (int &n) {
		char c;
		while (!isdigit(c = read_ch()));
        n = 0;
		do {
			n = 10 * n + c - '0';
		} while (isdigit(c = read_ch()));
		return *this;
	}
};
class OutParser {
private:
    FILE *fout;
    char *buff;
    int sp;
 
    void write_ch(char ch) {
        if (sp == BUFSIZE) {
            fwrite(buff, 1, BUFSIZE, fout);
            sp = 0;
            buff[sp++] = ch;
        } else {
            buff[sp++] = ch;
        }
    }
 
 
public:
    OutParser(const char* name) {
        fout = fopen(name, "w");
        buff = new char[BUFSIZE]();
        sp = 0;
    }
    ~OutParser() {
        fwrite(buff, 1, sp, fout);
        fclose(fout);
    }
 
    OutParser& operator << (int vu32) {
        if (vu32 <= 9) {
            write_ch(vu32 + '0');
        } else {
            (*this) << (vu32 / 10);
            write_ch(vu32 % 10 + '0');
        }
        return *this;
    }

 
    OutParser& operator << (char ch) {
        write_ch(ch);
        return *this;
    }
};
const int NMAX = 1e5;

vector <int> edges[NMAX + 1];
int depth[NMAX + 1];
int father[NMAX + 1];
int jump[NMAX + 1];

void dfs( int node ) {
    for ( auto vec : edges[node] ) {
        depth[vec] = depth[node] + 1;
        if ( depth[node] - depth[jump[node]] == depth[jump[node]] - depth[jump[jump[node]]] ) jump[vec] = jump[jump[node]];
        else jump[vec] = node;
        dfs( vec );
    }
}

int kthAnc( int a, int targetD ) {
    while ( depth[a] > targetD ) {
        if ( depth[jump[a]] >= targetD ) a = jump[a];
        else a = father[a];
    }
    return a;
}
int lca( int a, int b ) {
    if ( depth[a] < depth[b] ) swap( a, b );
    a = kthAnc( a, depth[b] );
    while ( a != b ) {
        if ( jump[a] != jump[b] ) {
            a = jump[a];
            b = jump[b];
        } else {
            a = father[a];
            b = father[b];
        }
    }
    return a;
}
int main() {
    InParser fin( "lca.in" );
    OutParser fout( "lca.out" );
    int n, q;
    fin >> n >> q;
    for ( int i = 2; i <= n; i ++ ) {
        fin >> father[i];
        edges[father[i]].push_back( i );
    }
    father[1] = jump[1] = 1;
    dfs( 1 );
    for ( int i = 1, a, b; i <= q; i ++ ) {
        fin >> a >> b;
        fout << lca( a, b ) << '\n';
    }
    return 0;
}