dijkstra優先隊列最佳化(代碼抄襲。。。)

來源:互聯網
上載者:User

標籤:

1.建立一個結構體以存放鄰接表:struct edge(int to,dist; edge*next)

2.每一次讀入一組資料,每個節點都有一個鏈表,裡面儲存著從該節點出發的所有邊:

void add( int u , int v , int d ) {   pt -> to = v;   pt -> dist = d;   pt -> next = head[ u ];    //head存放第一條邊,且同一個起點的各條邊在鄰接表中的書序和讀入順序正好相反;               head[ u ] = pt++;          //這裡pt++是申請記憶體吧;}                                     //同時注意無向圖每條邊會在鄰接表中出現兩次; 3.重磅戲,優先隊列然後加個什麼什麼函數(記住就好了吧==): struct node {  int x , d;                                                     //x是編號,d是距離起點的距離,加一個d[]數組很明顯避免了對鏈表的遍曆;  bool operator < ( const node &rhs ) const {  return d > rhs.d;  }}; int d[ maxn ];priority_queue< node > Q; 4.然後很簡單啦,明白dijkstra原理就不難寫出來了:   void dijkstra( int S ) {    clr( d , inf );    d[ S ] = 0;    Q.push( ( node ) { S , 0 } );    while( ! Q.empty() ) {        node o = Q.top();        Q.pop();        int x = o.x , dist = o.d;        if( dist != d[ x ] ) continue;        for( edge* e = head[ x ] ; e ; e = e -> next ) {               int to = e -> to;               if( d[ to ] > dist + e -> dist ) {                    d[ to ] = dist + e -> dist;                    Q.push( ( node ) { to , d[ to ] } );               }      }   }} 完了。。。大概只有我這種低智商的才需要慢慢分析吧==加油          

dijkstra優先隊列最佳化(代碼抄襲。。。)

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.