How far away ?hdu 2586 (spfa)

http://acm.hdu.edu.cn/showproblem.php?pid=2586

题意:现给出一些城市间的距离长度,问你A城市到B城市最短距离是多少。

分析:由于点较多 n(2<=n<=40000),所以需要用到spfa算法。一开始没注意是双向的,导致数组开小,wa了一次。。。。

#include<stdio.h>
#include<string.h>
#include<math.h>
#include<queue>
#include<algorithm>
using namespace std;
typedef  long long LL;

#define maxn 450000
#define oo 0x3f3f3f3f
int head[maxn], v[maxn], dist[maxn], cnt;

struct node
{
    int u, v, w, next;
}maps[maxn];

void Add(int u, int v, int w)
{
    maps[cnt].v = v;
    maps[cnt].w = w;
    maps[cnt].next = head[u];
    head[u] = cnt++;
}


///spfa模板
void spfa(int a, int b)
{
    memset(v, 0, sizeof(v));
    queue<int>Q;
    Q.push(a);
    v[a] = 1;

    while(Q.size())
    {
        int p = Q.front();
        Q.pop();
        v[p] = 0;

        for(int i=head[p]; i!=-1; i=maps[i].next)
        {
            int q = maps[i].v;

            if(dist[q]>dist[p]+maps[i].w)
            {
                dist[q] = dist[p]+maps[i].w;
                if(!v[q])
                {
                    v[q]=1;
                    Q.push(q);
                }
            }
        }
    }

    printf("%d
", dist[b]);
}

int main()
{
    int T, n, m;

    scanf("%d", &T);

    while(T --)
    {
        scanf("%d %d", &n, &m);

        int a, b, c;
        memset(maps, 0, sizeof(maps));
        memset(head, -1, sizeof(head));
        cnt = 0;

        for(int i=1; i<n; i++)
        {
            scanf("%d %d %d", &a, &b, &c);
            Add(a, b, c);
            Add(b, a, c);
        }

        while(m --)
        {
            scanf("%d %d", &a, &b);

            for(int i=1; i<=n; i++)
                dist[i] = oo;

            dist[a] = 0;

            spfa(a, b);
        }

    }
    return 0;
}
View Code