谭松松的旅游计划
Time Limit: 3000/1000MS (Java/Others) Memory Limit: 65535/65535KB (Java/Others)
谭松松是一个爱旅游的人,他非常的热爱旅游,即便身体被掏空也要坚持旅游。喵蛤王国由N个城市组成,由N-1条道路连通,每条道路长度为ci,使得任意两座城市都能相互到达。谭松松有M个旅游计划,每个旅游计划有一个起点ai,一个终点bi,所以谭松松想知道,对于每个旅游计划,从起点到终点的最短路长度为多少?
Input
第一行两个整数N(2≤N≤100000,),M(1≤M≤100000),表示城市个数,谭松松的旅游计划个数。
接下来N-1行,每行三个整数li,ri,ci(1≤ci≤10000),表示li号城市和ri号城市之间有一条长度为ci的道路。
接下来M行,每行两个整数ai,bi表示旅游计划的起点和终点。
Output
输出M行,表示每个旅游计划的最短距离。
Sample input and output
Sample Input | Sample Output |
---|---|
7 6 1 2 5 1 3 4 3 7 7 2 4 4 2 5 3 5 6 2 1 2 4 7 6 3 3 2 5 4 7 6 | 5 20 14 9 7 21 |
LCA知识点:http://blog.csdn.net/cxllyg/article/details/7635992
这里我用的第二种写法做的,第三种暂时还没看懂。。
代码如下:
#include <cstdio>
#include <vector>
#include <algorithm>
using namespace std;
int n,m;
struct node
{
int to,p;
};
vector <node> v[100010];
int depth[100010],cost[100010],vis[100010],fa[100010];//深度 权值 标记访问 父节点
void dfs(int x,int dep)
{
for(int i=0;i<v[x].size();i++)
{
int to=v[x][i].to;
int p=v[x][i].p;
if(vis[to]==1)
{
continue;
}
depth[to]=dep+1;
cost[to]=p;
fa[to]=x;
vis[to]=1;
dfs(to,dep+1);
}
}
int main()
{
scanf("%d%d",&n,&m);
node tmp;
for(int i=1;i<n;i++)
{
int s,e,p;
scanf("%d%d%d",&s,&e,&p);
tmp.to=s;
tmp.p=p;
v[e].push_back(tmp);
tmp.to=e;
v[s].push_back(tmp);
}
vis[1]=1;
dfs(1,0);//构造树
while(m--)
{
int x,y;
scanf("%d%d",&x,&y);
int ans=0;
while(depth[x]>depth[y])//把x和y移到同一高度
{
ans=ans+cost[x];
x=fa[x];
}
while(depth[x]<depth[y])//把x和y移到同一高度
{
ans=ans+cost[y];
y=fa[y];
}
while(x!=y)//x和y齐头并进
{
ans=ans+cost[x]+cost[y];
x=fa[x];
y=fa[y];
}
printf("%d\n",ans);
}
return 0;
}