HDU - 2586 - How far away ? (最短路)
There are n houses in the village and some bidirectional roads connecting them. Every day peole always like to ask like this “How far is it if I want to go from house A to house B”? Usually it hard to answer. But luckily int this village the answer is always unique, since the roads are built in the way that there is a unique simple path(“simple” means you can’t visit a place twice) between every two houses. Yout task is to answer all these curious people.
Input
First line is a single integer T(T<=10), indicating the number of test cases.
For each test case,in the first line there are two numbers n(2<=n<=40000) and m (1<=m<=200),the number of houses and the number of queries. The following n-1 lines each consisting three numbers i,j,k, separated bu a single space, meaning that there is a road connecting house i and house j,with length k(0<k<=40000).The houses are labeled from 1 to n.
Next m lines each has distinct integers i and j, you areato answer the distance between house i and house j.
Output
For each test case,output m lines. Each line represents the answer of the query. Output a bland line after each test case.
Sample Input
2
3 2
1 2 10
3 1 15
1 2
2 3
2 2
1 2 100
1 2
2 1
Sample Output
10
25
100
100
题目大意:
给你一个带权无向图,有n个顶点,n-1条边。然后有m次询问,每次询问 有 a b两个数,需要输出a b 之间的最短路。
抽象一下,就是求任意两点之间的最短路。
解题思路:
任意两点最短路???首先想到的肯定是Floyd算法,但是。。。数据量n=1e4…复杂度0(n3)肯定是不行的
然后我就考虑把询问里的数按出现次序排序,然后先用Dijkstra跑出现次数最多的顶点w为起点的最短路,然后把结果用个 标记数组 book[i][j]记录下来,然后遇到已经跑过的最短路,也就是book数组里有的就直接输出,然后每次都跑Dijkstra。。。虽然i想的很美好,但是却给我显示超内存了???
无奈之下,上网搜了一波题解
题解上用dfs每次询问,找一下最短路。。。简单粗暴又实用。。。数据量是1e4 边数 也是1e4的数据量 询问数<100…所以也不会超时。。
搜索的时候我们用个标记数组vis[]表示这个点是否经过过,然后遇到中终点就输出结果,不是终点就继续dfs。
AC代码:
#include <iostream>
#include <cstdio>
#include <cstring>
#include <queue>
#define inf 0x3f3f3f3f
using namespace std;
const int maxn=40009;
int vis[maxn];
int head[maxn];
int cnt=0;
int n,m;
struct node{
int to;
int val;
int next;
}side[maxn*2];
void init()
{
memset(head,-1,sizeof(head));
memset(vis,0,sizeof(vis));
cnt=0;
}
void add(int x,int y,int w)
{
side[cnt].to=y;
side[cnt].val=w;
side[cnt].next=head[x];
head[x]=cnt++;
}
void dfs(int a,int b,int step)
{
vis[a]=1;
for(int i=head[a];i!=-1;i=side[i].next)
{
int k=side[i].to;
if(vis[k])
continue;
if(k==b)
{
cout<<step+side[i].val<<endl;
return ;
}
else
{
dfs(k,b,step+side[i].val);
}
}
}
int main()
{
int T;
cin>>T;
while(T--)
{
cin>>n>>m;
init();
for(int i=0;i<n-1;i++)
{
int a,b,c;
scanf("%d %d %d",&a,&b,&c);
add(a,b,c);
add(b,a,c);
}
while(m--)
{
int a,b;
cin>>a>>b;
memset(vis,0,sizeof(vis));
dfs(a,b,0);
}
}
return 0;
}