Bellman-Ford基础上的队列优化,效率比较高,可以检测负环。
const int maxn = 110;
const int max_int = ~(1<<31);
const int min_int = (1<<31);
bool inq[maxn];
int cost[maxn][maxn], dist[maxn], cnt[maxn], q[maxn], front, rear;
//[0,max_int]
int min(int a, int b){
return a < b ? a : b;
}
int spfa(int s){
memset(inq, 0, sizeof(inq));
memset(cnt, 0, sizeof(cnt));
for(int i = 0; i < n; ++i){
dist[i] = max_int;
}
dist[s] = 0;
front = rear = 0;
q[rear++] = s;
inq[s] = true;
++cnt[s];
while(front != rear){
int now = q[front++];
inq[now] = false;
for(int i = 0; i < n; ++i)if(cost[now][i] != max_int && dist[i] > dist[now] + cost[now][i]){
dist[i] = dist[i] + cost[now][i];
if(!inq(i)){
q[rear++] = i;
inq[i] = true;
++cnt[i];
}
if(cnt[i] > n){
return -1;
}
}
}
}