【弱校胡策】 DQS 的 tree|倍增LCA

分类讨论下就行

不知道正解咋样

好像只有我没A T2

#include <cstdio>
#include <cstring>
#include <iostream>
#include <algorithm>
using namespace std;
#define LL long lon
const int MAXN=1e5+10;
const int LOGN=17+1;
int depth[MAXN],to[MAXN][LOGN],mmax[MAXN][LOGN];
int team[MAXN],head,tail;
int tot,g[MAXN],num[MAXN*2],nnext[MAXN*2],cost[MAXN*2];
void add(int x,int y,int z)
{
	tot++;
	nnext[tot]=g[x];
	g[x]=tot;
	num[tot]=y;
	cost[tot]=z;
}
int ask(int x,int y)
{
	int ans=mmax[0][0];
	if(depth[x]<depth[y]) swap(x,y);
	for(int i=17;i>=0;i--)
		if(depth[to[x][i]]>=depth[y])
		{
			ans=max(ans,mmax[x][i]);
			x=to[x][i];
		}
	for(int i=17;i>=0;i--)
		if(to[x][i]!=to[y][i])
		{
			ans=max(ans,max(mmax[x][i],mmax[y][i]));
			x=to[x][i];
			y=to[y][i];
		}
	if(x!=y)
	{
		ans=max(ans,max(mmax[x][0],mmax[y][0]));
		x=to[x][0];
		y=to[y][0];
	}
	return ans;
}
int q_lca(int x,int y)
{
	if(depth[x]<depth[y]) swap(x,y);
	for(int i=17;i>=0;i--)
		if(depth[to[x][i]]>=depth[y])
			x=to[x][i];
	if(x==y) return x;
	for(int i=17;i>=0;i--)
		if(to[x][i]!=to[y][i])
		{
			x=to[x][i];
			y=to[y][i];
		}
	return to[x][0];
}
int main()
{
	freopen("tree.in","r",stdin);
	freopen("tree.out","w",stdout);
	int n,m;
	scanf("%d",&n);
	for(int i=1;i<n;i++)
	{
		int x,y,z;
		scanf("%d %d %d",&x,&y,&z);
		add(x,y,z);
		add(y,x,z);
	}
	team[++tail]=1;depth[1]=1;
	while(head<tail)
	{
		int x=team[++head];
		for(int i=1;i<=17;i++) 
		{
			mmax[x][i]=max(mmax[x][i-1],mmax[to[x][i-1]][i-1]);
			to[x][i]=to[to[x][i-1]][i-1];
		}
		for(int i=g[x];i;i=nnext[i])
		{
			int tmp=num[i];
			if(tmp==to[x][0]) continue;
			depth[tmp]=depth[x]+1;
			to[tmp][0]=x;
			mmax[tmp][0]=cost[i];
			team[++tail]=tmp;
		}
	}
	scanf("%d",&m);
	for(int i=1;i<=m;i++)
	{
		int x,y,q;
		scanf("%d %d %d",&x,&y,&q);
		int lca=q_lca(x,y);
		int lcax=q_lca(x,q);
		int lcay=q_lca(y,q);
		int qlca=q_lca(lca,q);
		if((lca==qlca&&(lcax==q||lcay==q))) printf("%d\n",0);
		else 
		{ 
			int ans=ask(q,lca);
			if(qlca!=lcax) ans=min(ans,ask(q,lcax));
			if(qlca!=lcay) ans=min(ans,ask(q,lcay));
			printf("%d\n",ans);
		}
	}
	fclose(stdin);
	fclose(stdout);
	return 0;
}


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值