标签:
ECJTU 2009 Spring Contest
题目大意:一个村庄有N个房子和一些双向的路,人们总是喜欢问"A到B有多远呢",一般是很难
回答的,毕竟有很多种答案。所幸,答案是唯一的,A到B总是有唯一的路径到达。第一行是T组
数据。每组数据第一行是N个房子和M条询问。接下来N-1行每行是u v w,表示从房子u到房子v
的距离是w。接下来是M行询问。每行是u v,表示询问房子u到房子v的距离,最后输出所有的询
问结果。
思路:整个村庄房子和路可看成一棵树,设根结点为房子1,询问u到房子v的距离,其实就是求u
到根结点的距离 + v到根结点的距离 - 2*(u,v)最近公共祖先到根结点的距离。这道题和POJ1986
是一样的,可参考:http://blog.csdn.net/lianai911/article/details/42300301
#include<iostream> #include<algorithm> #include<cstdio> #include<cstring> using namespace std; const int MAXN = 80080; const int MAXQ = 440; struct EdgeNode { int to; int next; int lca; }Edges[MAXN],QEdges[MAXQ]; int Head[MAXN],QHead[MAXN],father[MAXN],Dist[MAXN]; bool vis[MAXN]; int find(int x) { if(x != father[x]) father[x] = find(father[x]); return father[x]; } void LCA(int u) { father[u] = u; vis[u] = true; for(int k = Head[u]; k != -1; k = Edges[k].next) { if(!vis[Edges[k].to]) { Dist[Edges[k].to] = Dist[u] + Edges[k].lca; LCA(Edges[k].to); father[Edges[k].to] = u; } } for(int k = QHead[u]; k != -1; k = QEdges[k].next) { if(vis[QEdges[k].to]) { QEdges[k].lca = Dist[u] + Dist[QEdges[k].to] - 2*Dist[find(QEdges[k].to)]; QEdges[k^1].lca = QEdges[k].lca; } } } int main() { int T,N,M,u,v,w; scanf("%d",&T); while(T--) { scanf("%d%d",&N,&M); memset(Dist,0,sizeof(Dist)); memset(father,0,sizeof(father)); memset(vis,false,sizeof(vis)); memset(Edges,0,sizeof(Edges)); memset(QEdges,0,sizeof(QEdges)); memset(Head,-1,sizeof(Head)); memset(QHead,-1,sizeof(QHead)); int id = 0; for(int i = 0; i < N-1; ++i) { scanf("%d%d%d",&u,&v,&w); Edges[id].to = v; Edges[id].lca = w; Edges[id].next = Head[u]; Head[u] = id++; Edges[id].to = u; Edges[id].lca = w; Edges[id].next = Head[v]; Head[v] = id++; } int ip = 0; for(int i = 0; i < M; ++i) { scanf("%d%d",&u,&v); QEdges[ip].to = v; QEdges[ip].next = QHead[u]; QHead[u] = ip++; QEdges[ip].to = u; QEdges[ip].next = QHead[v]; QHead[v] = ip++; } LCA(1); for(int i = 0; i < ip; i += 2) printf("%d\n",QEdges[i].lca); } return 0; }
HDU2586 How far away ?【最近公共祖先】【Tarjan-LCA算法】
标签:
原文地址:http://blog.csdn.net/lianai911/article/details/42301329