hdu2544最短路径spfa模版题

 
#include <cstdlib>

#include <iostream>

#include<vector>

#include<queue>

using namespace std; struct edge { int from,to,cost; }; const int MAXN=111; const int MAX=999999;

vector<edge>v[MAXN]; bool in_queue[MAXN]; int dist[MAXN]; void spfa(int p) {

    queue<int>q; int i=0;

    memset(in_queue,0,sizeof(in_queue)); for(i=0;i<=MAXN;i++) {

        dist[i]=MAX; } while(!q.empty()) {

        q.pop(); }

    dist[p]=0;

    q.push(p);

    in_queue[p]=1; while(!q.empty()) { int cur=q.front(); int i=0;

        q.pop();

        in_queue[cur]=0; for(i=0;i<=int(v[cur].size())-1;i++) { int cost=v[cur][i].cost+dist[cur]; int to=v[cur][i].to; if(cost<dist[to]) {

                dist[to]=cost; if(!in_queue[to]) {

                    q.push(to);

                    in_queue[to]=1; } } } } } int main(int argc, char *argv[]) { int n,m; while((cin>>n>>m)&&(!((n==0)&&(m==0)))) { int i=0; for(i=0;i<=n+1;i++) {

            v[i].clear(); } while(m--) { int from,to,cost;

            cin>>from>>to>>cost;

            edge e={from,to,cost};

            v[e.from].push_back(e);

            swap(e.from,e.to);

            v[e.from].push_back(e); }

        spfa(1);

        cout<<dist[n]<<endl; }

    //system("PAUSE");

 return EXIT_SUCCESS; }
 

  

你可能感兴趣的:(最短路径)