Cod sursa(job #3172320)

Utilizator NutaAlexandruASN49K NutaAlexandru Data 20 noiembrie 2023 14:54:30
Problema Lowest Common Ancestor Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 2.27 kb
#include <bits/stdc++.h>
using namespace std;
#define all(x) x.begin(),x.end()
#define pb push_back
using i64=long long;
class InParser {
private:
	FILE *fin;
	char *buff;
	int sp;

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

public:
	InParser(const char* nume) {
		fin = fopen(nume, "r");
		buff = new char[4096]();
		sp = 4095;
	}

	InParser& operator >> (int &n) {
		char c;
		while (!isdigit(c = read_ch()) && c != '-');
		int sgn = 1;
		if (c == '-') {
			n = 0;
			sgn = -1;
		} else {
			n = c - '0';
		}
		while (isdigit(c = read_ch())) {
			n = 10 * n + c - '0';
		}
		n *= sgn;
		return *this;
	}

	InParser& operator >> (long long &n) {
		char c;
		n = 0;
		while (!isdigit(c = read_ch()) && c != '-');
		long long sgn = 1;
		if (c == '-') {
			n = 0;
			sgn = -1;
		} else {
			n = c - '0';
		}
		while (isdigit(c = read_ch())) {
			n = 10 * n + c - '0';
		}
		n *= sgn;
		return *this;
	}
};
const int inf=1e9;
const int N=1e5;
const int M=2e6;
vector<int>out,node_query,rez,t;
vector<vector<int>>g,ind;
int n,m;
void init_dsu()
{
    t.resize(n);
    iota(all(t),0);
}
int root(int x)
{
    if(x!=t[x])
    {
        t[x]=root(t[x]);
    }
    return t[x];
}
void unite(int x,int y)
{
    t[root(y)]=root(x);
}

void dfs1(int nod=0)
{
    static int acm=-1;
    for(auto &c:g[nod])
        dfs1(c);
    out[nod]=++acm;
}
void dfs2(int nod=0)
{
    for(auto &c:g[nod])
    {
        dfs2(c);
        unite(nod,c);
    }
    for(auto &c:ind[nod])
    {
        rez[c]=root(node_query[c]);
    }
}
void resize_n()
{
    g.resize(n);
    ind.resize(n);
    out.assign(n,-1);
    init_dsu();
    node_query.assign(m,-1);
    rez.assign(m,-1);
}
main()
{
    InParser cin("lca.in");
    ofstream cout("lca.out");
    cin>>n>>m;
    resize_n();
    for(int i=1;i<n;i++)
    {
        int x;
        cin>>x;
        g[x-1].pb(i);
    }
    dfs1();
    for(int i=0;i<m;i++)
    {
        int x,y;
        cin>>x>>y;
        x--;
        y--;
        if(out[x]>out[y])
            swap(x,y);
        ind[y].pb(i);
        node_query[i]=x;
    }
    dfs2();
    for(auto &c:rez)
        cout<<c+1<<'\n';
}