最短路——SPFA

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;
			}
		}
	}
}


發佈了102 篇原創文章 · 獲贊 3 · 訪問量 9萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章