标签:des style blog http java color os 数据
Problem Description
After World War X, a lot of cities have been seriously damaged, and we need to rebuild those cities. However, some materials needed can only be produced in certain places. So we need to transport these materials from city to city. For most of roads had been totally destroyed during the war, there might be no path between two cities, no circle exists as well.
Now, your task comes. After giving you the condition of the roads, we want to know if there exists a path between any two cities. If the answer is yes, output the shortest path between them.
Input
Input consists of multiple problem instances.For each instance, first line contains three integers n, m and c, 2<=n<=10000, 0<=m<10000, 1<=c<=1000000. n represents the number of cities numbered from 1 to n. Following m lines, each line has three integers i, j and k, represent a road between city i and city j, with length k. Last c lines, two integers i, j each line, indicates a query of city i and city j.
Output
For each problem instance, one line for each query. If no path between two cities, output “Not connected”, otherwise output the length of the shortest path between them.
Sample Input
5 3 2 1 3 2 2 4 3 5 2 3 1 4 4 5
Sample Output
Not connected 6
题意:给你n给点,m条边,有c次询问,每次询问u,v两个点,你需要判断u,v是否连通,u,v的最短距离是多少。
::对于是否连通直接用并查集就可以了,对于连通的两个点最短距离怎么求呢。
数据很大,不允许每次询问都跑一次最短路的算法,那么就考虑一下一劳永逸的办法,有没有办法经过预处理,每次询问都能快速给出答案。
注意到这是无欢图,那没就转化成树的做法。
对于单个连通分量随意取一点,令其为根,进行dfs遍历,得到每个点到根结点的距离,保存起来(我这里用dp保存),并且得到一个dfs遍历的寻列,求出每两个点的lca。如何求lca具体看
lca –> rmq. 那么对于询问在同一个连通分量的两个的距离dis(u,v) = dp(u)+dp(v)-2*dp(lca(u,v));//u到根结点的距离+v到根结点的距离-(u,v)最早公共祖先到根结点的距离的2倍
view code
hdu 2874 Connections between cities(lca->rmq),布布扣,bubuko.com
hdu 2874 Connections between cities(lca->rmq)
标签:des style blog http java color os 数据
原文地址:http://www.cnblogs.com/zyx1314/p/3873009.html