hdu 2586

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;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值