標籤:end push color oid 多次 沒有 隊列 三次 amp
題目很簡單,, 但是wa了三次,, 用<vector>之前一定要記得clear()。。。
簡單說下 spfa的問題 和bell_forman有點類似 每次取出一個點 然後更新 並把更新了的節點入隊(更新的值可能會影響到最優解) 當隊列為空白的時候演算法結束(無法最佳化)
這裡的vis數組是為了防止重複入隊 但每個節點可能多次入隊 所以在拿出來的時候 vis標記要消去
最後說下負環的問題 引用一下
對於不存在負權迴路的圖來說,上述演算法是一定會結束的。因為演算法在反覆最佳化各個最短路徑長度,總有一個時刻會進入“無法再最佳化”的局面,此時一旦隊列讀空,演算法就結束了。
然而,如果圖中存在一條權值為負的迴路,就糟糕了,演算法會在其上反覆運行(因為d[]加上一個負數肯定變下了,所以在有負環的情況下,會不斷有數進入隊列),通過“繞圈”來
無休止地試圖減小某些相關點的最短路徑值。假如我們不能保證圖中沒有負權迴路,一種“結束條件”是必要的。這種結束條件是什麼呢?
思考Bellman-Ford演算法,它是如何結束的?顯然,最樸素的Bellman-Ford演算法不管迴圈過程中發生了什麼,一概要迴圈|V|-1遍才肯結束。憑直覺我們可以感到,SPFA演算法
“更聰明一些”,就是說我們可以猜測,假如在SPFA中,一個點進入隊列——或者說一個點被處理——超過了|V|次,那麼就可以斷定圖中存在負權迴路了。(http://www.cnblogs.com/jiangu66/p/3235361.html)
23號比賽加油~
#include<iostream>#include<vector>#include<queue>#include<cstring>#define E 1001#define V 101#define inf 0x3f3f3f3fusing namespace std;struct node{ int point,cost;};vector<node> fuck[V];int n,m;void dijstra(int s){ int d[V]; priority_queue<int> q; for(int i=1;i<=n;i++) d[i]=inf; d[s]=0; q.push(s); while(!q.empty()) { int now=q.top(); q.pop(); for(int i=0;i<fuck[now].size();i++) { node temp=fuck[now][i]; if(d[temp.point]>d[now]+temp.cost) { q.push(temp.point); d[temp.point]=d[now]+temp.cost; } } } cout<<d[n]<<endl;}//void spfa(int s){ int vis[V]; int d[V],ret[V]; for(int i=1;i<=n;i++) d[i]=inf,vis[i]=ret[i]=0; d[s]=0; queue<int> q; q.push(s); ret[s]++; vis[s]=1; while(!q.empty()) { int now=q.front(); q.pop(); vis[now]=0; for(int i=0;i<fuck[now].size();i++) { node temp=fuck[now][i]; if(d[temp.point]>d[now]+temp.cost) { d[temp.point]=d[now]+temp.cost; if(vis[temp.point]==0) { vis[temp.point]=1; ret[temp.point]++; q.push(temp.point); if(ret[temp.point]>V) { cout<<-1<<endl; return ; } } } } } cout<<d[n]<<endl;}int main(){ while(cin>>n>>m) { if(n==0&&m==0) break; for(int i=1;i<=n;i++) fuck[i].clear(); for(int i=1;i<=m;i++) { int x,y,cost; cin>>x>>y>>cost; node temp; temp.cost=cost; temp.point=x; fuck[y].push_back(temp); temp.point=y; fuck[x].push_back(temp); } dijstra(1); //spfa(1); } return 0;}
複習最短路 spfa+dijstra堆最佳化