模板求优化,吸了氧还是会T
查看原帖
模板求优化,吸了氧还是会T
261932
qpdk777楼主2020/7/28 21:28

求dalao帮忙看看怎么优化

orzorz

#include<iostream>
#include<cstdio>
#include<vector>
typedef long long int ll;
using namespace std;

ll n,m,s,x,y,a,b;
ll fa[500010],dep[500010],anc[20][500010];
vector<ll> con[500010];

void build(ll root){
	dep[root] = dep[fa[root]]+1;
	anc[0][root] = fa[root];
	for(int i = 1; (1<<i)<dep[root]; ++i)
		anc[i][root] = anc[i-1][anc[i-1][root]];
	for(int i = 0; i <= con[root].size()-1; ++i){
		if(con[root][i] == fa[root]) continue;
		fa[con[root][i]] = root;
		build(con[root][i]);
	}
}

ll lca(ll a,ll b){
	if(dep[a]>dep[b]) swap(a,b);
	for(int i = 19; i >= 0; --i)
		if(dep[anc[i][b]] >= dep[a])
			b = anc[i][b];
	if(a==b) return a;
	for(int i = 19; i >= 0; --i){
		if(anc[i][a] != anc[i][b]){
			a = anc[i][a];
			b = anc[i][b];
		}
	}
	return fa[a];
}

int main(){
	ios::sync_with_stdio(false),cin.tie(NULL),cout.tie(NULL);
	cin>>n>>m>>s;
	for(int i = 1; i <= n-1; ++i){
		cin>>x>>y;
		con[x].push_back(y);
		con[y].push_back(x);
	}
	build(s);
	for(int i = 1; i <= m; ++i){
		cin>>a>>b;
		cout<<lca(a,b)<<endl;
	}
	
	return 0;
}
2020/7/28 21:28
加载中...