複習最短路 spfa+dijstra堆最佳化

來源:互聯網
上載者:User

標籤: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 0x3f3f3f3f
using 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堆最佳化

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.