HDU 2544 (SPFA)

模版的最短路问题.......刚学了SPFA.......先练练手额            STL是个神奇的东东...........

#include <iostream>
#include <algorithm>
#include <cmath>
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <string>
#include <vector>
#include <set>
#include <queue>
#include <stack>
#include <climits>//形如INT_MAX一类的
#define MAX 150
#define INF 0x7FFFFFFF
# define eps 1e-5
using namespace std;
struct node
{
    int value;
    int s;
};
vector<node>edge[MAX];
int n,m,dist[MAX],visit[MAX];

void spfa(int v0)
{
    int i,j;
    queue<int> q;
    for(i=1; i<=n; i++)
    {
        dist[i] = INF;
    }
    dist[1] = 0;
    q.push(v0);
    visit[v0] = 1;
    while(! q.empty())
    {
        int t = q.front();
        q.pop();
        visit[t] = 0;
        for(i=0; i<edge[t].size(); i++)
        {
            int value = edge[t][i].value;
            int s = edge[t][i].s;
            if(dist[s] > value + dist[t] )
            {
                dist[s] = value + dist[t];
                if(visit[s] == 0)//spfa改进之处,不会造成多余入队
                {
                    visit[s] = 1;
                    q.push(s);
                }
            }
        }
    }
}

int main()
{
    int i,j,a,b,c;
    while(scanf("%d%d",&n,&m))
    {
        if(n == 0 && m == 0)
            break;
        for(i=0; i<=n; i++)//全局的vector,每次都得清空
            edge[i].clear();
        node tt;
        memset(visit,0,sizeof(visit));
        for(i=0; i<m; i++)//构图,无向图
        {
            scanf("%d%d%d",&a,&b,&c);
            tt.s = b;
            tt.value = c;
            edge[a].push_back(tt);
            tt.s = a;
            edge[b].push_back(tt);
        }
        spfa(1);
        printf("%d\n",dist[n]);
    }
    return 0;
}
以后得熟练用邻接表啊~~~~~

你可能感兴趣的:(HDU 2544 (SPFA))