最短路之SPFA(单源)HDU 2544

#include <iostream>
#include <queue>
#include <algorithm>
#define MAXLEN 1005
#define inf 1<<29
using namespace std;
int map[MAXLEN][MAXLEN];
int vis[MAXLEN];
int dict[MAXLEN];
bool inq[MAXLEN];
void creat(int n)
{
    for (int i = 1; i <= n; i++)
        for (int j = 1; j <= n; j++)
        {
            if (i == j)
                map[i][j] = 0;
            else
                map[i][j] = map[j][i]= inf;
        }
}
void build_map(int m)
{
    for (int i = 0; i < m; i++)
    {
        int b, e, v;
        cin >> b >> e >> v;
        map[b][e] = map[e][b] = v;
    }
}
bool SPFA(int x, int n)
{
    queue <int> Q;
    memset(vis,0,sizeof(vis));
    memset(inq, false, sizeof(inq));
    for (int i = 0; i <= n; i++)
        dict[i] = inf;
    dict[x] = 0;
    inq[x]=true;
    Q.push(x);
    while (!Q.empty())
    {
        int q=Q.front();
        Q.pop();
        if(inq[q]==true)
            inq[q]=false;
        if (vis[q] > n)
            return false;
        vis[q]++;
        for (int i = 1; i <= n; i++)
        {
            if (map[q][i] < inf && dict[q] + map[q][i] < dict[i])
            {
                dict[i] = dict[q] + map[q][i];
                if(inq[i]==false)
                {
                    Q.push(i);
                    inq[i]=true;
                }
            }
        }
    }
    return true;
}
int main()
{
    int n,m;
    while(cin >> n >> m&& n!=0 && m!=0)
    {
        creat(n);
        build_map(m);
        int x=1;
        if (SPFA(x, n))
            cout << dict[n] << endl;
        
    }
}

 

posted @ 2018-08-09 08:37  小学弟-  阅读(113)  评论(0编辑  收藏  举报