How far away ? HDU - 2586 M次spfa

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


  我是跑了M 遍spfa 做出來的。LCA好做,要學一下


#include<queue>
#include<cstdio>
#include<cstring>
#include<algorithm>
using namespace std;
const int M=1e5;
const int inf=0x3f3f3f3f;
typedef long long ll;
struct node
{
    int now,to,ne;
    ll w;
}e[M];
int head[M],vis[M];
ll dis[M];
int cmp,t,n,m;
void init(int x,int y,ll w)
{
    e[cmp].now=x;
    e[cmp].ne=head[e[cmp].now];
    e[cmp].to=y;
    e[cmp].w=w;
    head[e[cmp].now]=cmp++;
}
void spfa(int st)
{
    memset(vis,0,sizeof(vis));
    for(int i=0;i<M;i++)
            dis[i]=inf;
    queue<int>q;
    dis[st]=0;
    vis[st]=1;
    q.push(st);
    while(q.size())
    {
        st=q.front();
        q.pop();
        vis[st]=0;
        for(int i=head[st];i!=-1;i=e[i].ne)
        {
            int to=e[i].to;
            if(dis[to]>dis[st]+e[i].w)
            {
                dis[to]=dis[st]+e[i].w;
                if(!vis[to])
                {
                    vis[to]=1;
                    q.push(to);
                }
            }
        }
    }
}
int main()
{
    ll sum,w;
    int now ,to;
    scanf("%d",&t);
    while(t--)
    {
        sum=0;cmp=0;
        for(int i=0;i<=40000;i++)
        head[i]=-1;
        scanf("%d%d",&n,&m);
        for(int i=1;i<n;i++)
        {
            scanf("%d%d%lld",&now,&to,&w);
            init(now,to,w);
            init(to,now,w);
        }
        int x,y;
        for(int i=0;i<m;i++)
        {
            scanf("%d%d",&x,&y);
            spfa(x);
            printf("%lld\n",dis[y]);
        }
    }
    return 0;
}



發佈了120 篇原創文章 · 獲贊 9 · 訪問量 1萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章