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 1Sample Output
10 25 100 100
题意概括:在一个村庄里有n个地方,这n个地方每两个之间都有一条唯一的双向道。进行m次询问,A到B的距离是多少?
解题思路:开始想的是一个最短路问题,但是数据量太大肯定会超时,然后想了半天没什么思路。最后看了一下杭电这题的讨论板,上面有说用LAC的,还有一个说用DFS+vector的。然后就看一下vector就是动态数组,搜了一下LAC相比之下还是用DFS和动态数组好些,动态数组好理解点,然后这题就相当于把每条路的起点当数组的下标,终点作为数组里面存的内容,然后把权值用另一个数组存一下(定义一个结构体),在深搜里面就把每个数组里面存的终点作为新的起点进入新的递归。直到找到终点。
代码:
#include<stdio.h>
#include<string.h>
#include<vector> //动态数组的头文件
using namespace std;
#define N 40010
struct edge
{
int v,w;
};
vector <struct edge>a[N];//定义一个结构体动态二维数组
int book[N],y,find;
void DFS(int x,int sum)
{
int i;
if(x==y)
{
printf("%d\n",sum);
find=1;
return ;
}
int l=a[x].size();//返回数组a[x]的元素个数
if(l==0||book[x]==1||find==1)
return ;
for(i=0;i<l;i++) //遍历每个阶段的起点x对应的数组
{
book[x]=1;
DFS(a[x][i].v,sum+a[x][i].w);
book[x]=0;
}
return ;
}
int main()
{
int i,j,t,m,n,u,v,w;
scanf("%d",&t);
while(t--)
{
scanf("%d%d",&n,&m);
edge e;
for(i=0;i<n;i++)
{
a[i].clear();//清空动态数组
}
for(i=1;i<n;i++)
{
scanf("%d%d%d",&u,&v,&w);
e.v=v;e.w=w; //把u,v分别当起点,将对应的终点和距离存入结构体中
a[u].push_back(e); //再将结构体插入对应的动态数组
e.v=u;e.w=w;
a[v].push_back(e);
}
int x;
for(i=0;i<m;i++)
{
scanf("%d%d",&x,&y);
find=0;
memset(book,0,sizeof(book));
DFS(x,0);
}
}
return 0;
}