http://acm.hdu.edu.cn/showproblem.php?pid=2544
邻接矩阵实现的SPFA求解单源最短路
#include <queue>
#include <stdio.h>
#include <string.h>
#include <iostream>
#include <algorithm>
using namespace std;
int V,E,G[110][110];
int dis[110],vis[110],enter[110];
bool SPFA(int scr)
{
for(int i=1; i<=V; i++)
{
dis[i] = 1e9;
vis[i] = 0;
enter[i] = 0;
}
dis[scr] = 0;
vis[scr] = 1;
enter[scr] = 1;
queue <int> Q;
Q.push(scr);
while(!Q.empty())
{
int tmp = Q.front();
Q.pop();
vis[tmp] = 0;
for(int i=1; i<=V; i++)
{
if(G[tmp][i] != 1e9)
{
if(dis[i] > dis[tmp] + G[tmp][i])
{
dis[i] = dis[tmp] + G[tmp][i];
if(!vis[i])
{
vis[i] = 1;
enter[i]++;
if(enter[i] >= V)
return false;
Q.push(i);
}
}
}
}
}
return true;
}
int main()
{
// freopen("in.txt", "r", stdin);
while(scanf("%d%d",&V,&E), V || E)
{
for(int i=1; i<=V; i++)
{
for(int j=1; j<=V; j++)
{
G[i][j] = 1e9;
}
G[i][i] = 0;
}
for(int i=1; i<=E; i++)
{
int from, to, cost;
scanf("%d%d%d",&from,&to,&cost);
G[from][to] = G[to][from] = min(G[from][to], cost);
}
SPFA(1);
printf("%d\n",dis[V]);
}
return 0;
}