hdu2544 最短路(SPFA算法)

SPFA算法,留个爪

 

#include <iostream>
#include <map>
using namespace std;
const int eps = 1000000;
const int size = 110;
int maze[size][size];
int n, m;
int dist[size];
int que[100*size];
bool visited[size];
void SPFA(int s)
{
     memset(visited, false, sizeof(visited));
     for (int i = 1; i <= n; i ++){
         dist[i] = eps;
         for (int j = 1; j <= n; j ++){
             if (!maze[i][j] && i != j){
                maze[i][j] = eps;               
             }
         }   
     }
     int rear, front;
     rear = 1, front = 0;
     que[front] = s;
     dist[s] = 0;
     visited[s] = true;
     while (front < rear){
           int u = que[front ++];
           visited[u] = false;
           for (int i = 1; i <= n; i ++){
               if (dist[i] > dist[u]+maze[u][i]){
                  dist[i] = dist[u] + maze[u][i];
                  if (!visited[i]){
                     que[rear ++] = i;
                     visited[i] = true;
                  }   
               }
           }
     }
}

int main()
{
   
    while (scanf("%d%d", &n, &m) != EOF && (m|n)){
          memset(maze, 0, sizeof(maze));
          while (m --){
                int a, b, c;
                scanf("%d%d%d", &a, &b, &c);
                if (maze[a][b] > c || maze[a][b] == 0){
                   maze[b][a] = maze[a][b] = c;
                }
          }
          SPFA(1);
          printf("%d\n", dist[n]);
    }
    return 0;   
}

你可能感兴趣的:(hdu2544 最短路(SPFA算法))