SPFA模板(SLF優化)

#include <stdio.h> 
#include <deque> 
#include <stack> 
#include <vector> 
#define MAXN 10001 
#define INF 99999999 
using namespace std; 
struct edge { 
 int to; 
 int weight; 
}; 
vector <edge> adjmap[MAXN]; 
bool in_queue[MAXN]; 
int in_sum[MAXN], dist[MAXN], path[MAXN], nodesum, edgesum; 
bool SPFA(int source) 
{ 
 deque <int> dq; 
 int x, to; 
 for (int i = 1; i <= nodesum; ++i) 
 { 
  in_sum[i] = 0; 
  in_queue[i] = false; 
  dist[i] = INF; 
  path[i] = -1; 
 } 
 dq.push_back(source); 
 ++in_sum[source]; 
 dist[source] = 0; 
 in_queue[source] = true; 
 while (!dq.empty()) 
 { 
  x = dq.front(); 
  dq.pop_front(); 
  in_queue[x] = false; 
  for (int i = 0, edgenumbersize = adjmap[x].size(); i < edgenumbersize; ++i) 
  { 
   to = adjmap[x][i].to; 
   if ((dist[x] < INF) && (dist[to] > dist[x] + adjmap[x][i].weight)) 
   { 
    dist[to] = dist[x] + adjmap[x][i].weight; 
    path[to] = x; 
    if (!in_queue[to]) 
    { 
     in_queue[to] = true; 
     ++in_sum[to]; 
     if (in_sum[to] == nodesum) 
      return false; 
     if (!dq.empty()) 
     { 
      if (dist[to] > dist[dq.front()]) 
       dq.push_back(to); 
      else 
       dq.push_front(to); 
     } 
     else 
      dq.push_back(to); 
    } 
   } 
  } 
 } 
 return true; 
} 
void Print_Path(int x) 
{ 
 stack <int> s; 
 int w = x; 
 while (path[w] != -1) 
 { 
  s.push(w); 
  w = path[w]; 
 } 
 printf("Vertex 1 to vertex %d shortest path length %d\n-> Path through: 1", x, dist[x]); 
 while (!s.empty()) 
 { 
  printf(" %d", s.top()); 
  s.pop(); 
 } 
 printf("\n"); 
} 
int main() 
{ 
 edge temp; 
 scanf("%d%d", &nodesum, &edgesum); 
 for (int i = 1; i <= nodesum; ++i) 
  adjmap[i].clear(); 
 for (int i = 1, s, e, w; i <= edgesum; ++i) 
 { 
  scanf("%d%d%d", &s, &e, &w); 
  temp.to = e; 
  temp.weight = w; 
  adjmap[s].push_back(temp); 
 } 
 if (SPFA(1)) 
  for (int i = 2; i <= nodesum; ++i) 
   Print_Path(i); 
 else 
  printf("Negative weight loop\n"); 
 return 0; 
}
...其實SPFA有時候相當的不穩定...
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章