hdu2586

#include<bits/stdc++.h>
using namespace std;

const int MAXN=40040;
const int MAXM=MAXN*2;
const int INF=0x3f3f3f3f;
struct e{
	int u,v,w;
	int nxt;
}edge[MAXM];
int head[MAXN],tot;
int N;
void init()
{
	tot=0;
	memset(head,-1,sizeof(head));
}


void add(int u,int v,int w){
	edge[tot].u=u;
	edge[tot].v=v;
	edge[tot].w=w;
	edge[tot].nxt=head[u];
	head[u]=tot++;
} 

int dep[MAXN],fa[MAXN],cost[MAXN];
int sumcost[MAXN][20],anc[MAXN][20];
bool vis[MAXN];

void bfs(int rt)
{
	memset(vis,false,sizeof(vis));
	queue<int> q;
	q.push(rt);
	fa[rt]=-1;
	dep[rt]=0;
	cost[rt]=0;
	vis[rt]=true;
	while (!q.empty())
	{
		int u=q.front();q.pop();
		for (int i=head[u];i!=-1;i=edge[i].nxt)
		{
			int v=edge[i].v;
			if (vis[v]) continue;
			dep[v]=dep[u]+1;
			cost[v]=edge[i].w;
			fa[v]=u;
			vis[v]=true;
			q.push(v);
		}
	}
}

void preprocess()
{
	memset(sumcost,0,sizeof(sumcost));
	for (int i=1;i<=N;i++)
	
	{
		anc[i][0]=fa[i];
		sumcost[i][0]=cost[i];
		for (int j=1;(1<<j)<=N;j++) anc[i][j]=-1;
		
	}
	for (int j=1;(1<<j)<=N;j++)
	{
	   for (int i=1;i<=N;i++) 
	     if (anc[i][j-1]!=-1)
	     {
	     	int a=anc[i][j-1];
	     	anc[i][j]=anc[a][j-1];
	     	sumcost[i][j]=sumcost[i][j-1]+sumcost[a][j-1];
		 }
	} 
}

int query(int p,int q){
	int tmp,log;
	if (dep[p]<dep[q]) swap(p,q);
	for (log=1;(1<<log)<=dep[p];log++);
	log--;
	int ans=0;
	for (int i=log;i>=0;i--)
	{ if (dep[p]-(1<<i)>=dep[q])
	    {ans+=sumcost[p][i];p=anc[p][i];
		}
	}
	if (p==q) return ans;
	for (int i=log;i>=0;i--)
	{
		if (anc[p][i]!=-1&&anc[p][i]!=anc[q][i])
		  {
		  	ans+=sumcost[p][i];p=anc[p][i];
		  	ans+=sumcost[q][i];q=anc[q][i];
		  }
	}
	ans+=cost[p];ans+=cost[q];
	return ans;
}

int main()
{
	int T;
	scanf("%d",&T);
	while (T--)
	{
		init();
		int Q;
		scanf("%d%d",&N,&Q);
		for (int i=0;i<N-1;i++){
			int u,v,w;
			scanf("%d%d%d",&u,&v,&w);
			add(u,v,w);
			add(v,u,w);
		}
		bfs(1);
		preprocess();
		while (Q--){
			int u,v;
			scanf("%d%d",&u,&v);
			printf("%d\n",query(u,v));
		}
	}
   return 0;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值