How far away ?
Time Limit: 1000msMemory Limit: 32768KB This problem will be judged on HDU. Original ID: 2586
64-bit integer IO format: %I64d Java class name: Main
Prev Submit Status Statistics Next
Type:
None
Tag it!
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
#include<iostream>
#include<cstring>
#include<cstdio>
#include<string>
using namespace std;
const int N=1000005;
struct node
{
int w,v,u,next;
}num[N];
int first[N];
int vis[N];
int n,m,k;
int s,e;
void add(int u,int v,int w)//创建邻接表
{
num[k].u=u;
num[k].v=v;
num[k].w=w;
num[k].next=first[u];//保存上个元素位置
first[u]=k++;//第几个数据
}
int dis=0,ok;
void dfs(int step,int ans)
{
if(step==e&&!ok)
{
ok=1;
dis=ans;
return ;
}
for(int i=first[step];i!=-1;i=num[i].next)
{
int v=num[i].v;
if(!vis[v])
{
vis[v]=1;
dfs(v,ans+num[i].w);
}
if(ok)
return ;
}
}
int main()
{
int t,i,j;
scanf("%d",&t);
while(t--)
{
scanf("%d%d",&n,&m);
for( i=0;i<=n+2;i++)
{
first[i]=-1;
}
int u,v,w;
k=0;
for( i=1;i<n;i++)//向邻接表中添加元素
{
scanf("%d%d%d",&u,&v,&w);
add(u,v,w);
add(v,u,w);
}
while(m--)//查询
{
memset(vis,0,sizeof(vis));
scanf("%d%d",&u,&v);
vis[u]=1;
s=u;
e=v;
ok=0;
dfs(u,0);
printf("%d\n",dis);
}
}
return 0;
}