标签:
题意:就是问两个节点间的距离
思路:又切了一道模版水题,不解释了,看不懂变量含义的可以看我写的这篇,解释的比较详细ZOJ 3195
#include <vector> #include <stdio.h> #include <string.h> #include <stdlib.h> #include <iostream> #include <algorithm> using namespace std; typedef long long ll; const int inf=0x3f3f3f3f; const int maxn=40010; struct edge{ int to,cost; edge(int a,int b){to=a;cost=b;} }; vector<edge>G[maxn]; int dp[maxn*2][20],L[maxn*2],E[maxn*2],dis[maxn],H[maxn]; bool vis[maxn]; int n,k; void dfs(int t,int deep){ k++;E[k]=t;L[k]=deep;H[t]=k; for(unsigned int i=0;i<G[t].size();i++){ edge e=G[t][i]; if(!vis[e.to]){ dis[e.to]=dis[t]+e.cost; vis[e.to]=1; dfs(e.to,deep+1); k++;E[k]=t;L[k]=deep; } } } void RMQ_init(){ for(int i=1;i<=2*n-1;i++) dp[i][0]=i; for(int i=1;(1<<i)<=2*n-1;i++){ for(int j=1;j+(1<<i)-1<=2*n-1;j++){ if(L[dp[j][i-1]]<L[dp[j+(1<<(i-1))][i-1]]) dp[j][i]=dp[j][i-1]; else dp[j][i]=dp[j+(1<<(i-1))][i-1]; } } } int RMQ(int le,int ri){ le=H[le];ri=H[ri]; if(le>ri) swap(le,ri); int kk=0; while((1<<(kk+1))<=ri-le+1) kk++; if(L[dp[le][kk]]<L[dp[ri-(1<<kk)+1][kk]]) return E[dp[le][kk]]; else return E[dp[ri-(1<<kk)+1][kk]]; } int main(){ int T,m,a,b,c; scanf("%d",&T); while(T--){ scanf("%d%d",&n,&m); memset(dis,0,sizeof(dis)); memset(vis,0,sizeof(vis)); for(int i=0;i<maxn;i++) G[i].clear(); for(int i=0;i<n-1;i++){ scanf("%d%d%d",&a,&b,&c); G[a].push_back(edge(b,c)); G[b].push_back(edge(a,c)); } k=0;vis[1]=1; dfs(1,1);RMQ_init(); while(m--){ scanf("%d%d",&a,&b); int ans=dis[a]+dis[b]-2*dis[RMQ(a,b)]; printf("%d\n",ans); } } return 0; }
标签:
原文地址:http://blog.csdn.net/dan__ge/article/details/51297912