LCA+换根DP 92分求调WA 11,13
查看原帖
LCA+换根DP 92分求调WA 11,13
1278879
wjxalex楼主2024/11/24 23:15
#include <iostream>
#include <cstring>
#include <vector>
#include <cstdio>
using namespace std;
typedef long long ll;
inline ll read(){
	ll s=0;
	char ch=getchar();
	while(ch<'0'||ch>'9'){
		ch=getchar();
	}
	while(ch>='0'&&ch<='9'){
		s=s*10+ch-'0';
		ch=getchar();
	}
	return s;
}
const ll N=200021;
const ll INF=1e16;
ll n,q;
ll c[N]={};
ll dp[N]={};
ll dep[N]={},lg[N]={},f[32][N]={},st[32][N]={},maxn[32][N]={};
struct E{
	ll v,w;
};
vector<E> edgs[N];
bool vis[N]={};
void dfs1(ll u){
	dp[u]=c[u];
	vis[u]=true;
	for(ll i=0;i<edgs[u].size();i++){
		ll v=edgs[u][i].v,w=edgs[u][i].w;
		if(vis[v]){
			continue;
		}
		dfs1(v);
		dp[u]=max(dp[u],dp[v]-w*2);
	}
}
void dfs2(ll u){
	vis[u]=true;
	for(ll i=0;i<edgs[u].size();i++){
		ll v=edgs[u][i].v,w=edgs[u][i].w;
		if(vis[v]){
			continue;
		}
		dp[v]=max(dp[u]-2*w,dp[v]);
		dfs2(v);
	}
}
void dfs3(ll u,ll fa){
	vis[u]=1;
	maxn[0][u]=dp[u];
	dep[u]=dep[fa]+1;
	if(u!=1){
		f[0][u]=fa;
	}
	for(ll i=1;i<=lg[dep[u]];i++){
		f[i][u]=f[i-1][f[i-1][u]];
		st[i][u]=st[i-1][u]+st[i-1][f[i-1][u]];
		maxn[i][u]=max(maxn[i-1][u],maxn[i-1][f[i-1][u]]);
	}
	for(ll i=0;i<edgs[u].size();i++){
		ll v=edgs[u][i].v,w=edgs[u][i].w;
		if(vis[v]){
			continue;
		}
		st[0][v]=w;
		dfs3(v,u);
	}
}
ll LCA(ll x,ll y){
	ll res=-INF,len=0;
	if(dep[x]<dep[y]){
		swap(x,y);
	}
	for(ll i=30;i>=0;i--){
		if(dep[f[i][x]]>=dep[y]){
			len+=st[i][x];
			res=max(res,maxn[i][x]);
			x=f[i][x];
		}
	}
	if(x==y){
		res=max(res,maxn[0][x]);
		return res-len;
	}
	for(ll i=30;i>=0;i--){
		if(f[i][x]!=f[i][y]){
			len+=st[i][x]+st[i][y];
			res=max(res,max(maxn[i][x],maxn[i][y]));
			x=f[i][x];
			y=f[i][y];
		}
	}
	len+=st[0][x]+st[0][y];
	res=max(res,max(maxn[1][x],maxn[1][y]));
	return res-len;
}
int main(){
	n=read();
	q=read();
	for(ll i=2;i<=n;i++){
		lg[i]=lg[i/2]+1;
	}
	for(ll i=1;i<=n;i++){
		c[i]=read();
	}
	for(ll i=1,u,v,w;i<n;i++){
		u=read();
		v=read();
		w=read();
		edgs[u].push_back({v,w});
		edgs[v].push_back({u,w});
	}
	dfs1(1);
	memset(vis,0,sizeof(vis));
	dfs2(1);
	memset(vis,0,sizeof(vis));
	dep[0]=-1;
	dfs3(1,0);
	for(ll i=1,x,y;i<=q;i++){
		x=read();
		y=read();
		cout<<c[x]+c[y]+LCA(x,y)<<endl;
	}
	return 0;
}
2024/11/24 23:15
加载中...