poj 1511 Invitation Cards(dijstra最佳化)

來源:互聯網
上載者:User

標籤:print   blank   push   nbsp   priority   efi   href   http   for   

題目連結:http://poj.org/problem?id=1511

題意:給出n個點和n條有向邊,求所有點到源點1的來回最短路之和(保證每個點都可以往返源點1)

題目比較簡單就是邊和點的個數有點多所以可以用dijstra+優先隊列這樣複雜度就可以到v*logn

 

#include <iostream>#include <cstring>#include <string>#include <vector>#include <queue>#include <cstdio>#define inf 1000000000using namespace std;const int M = 1e6 + 10;int n , m , a[M] , b[M] , c[M] , dis[M];struct TnT {    int v , w;};struct cmp {    bool operator() (int x , int y) {        return dis[x] > dis[y];    }};vector<TnT>vc[M];bool vis[M];void dij(int s) {    priority_queue<int , vector<int> , cmp>q;    memset(vis , false , sizeof(vis));    TnT gg;    q.push(s);    dis[s] = 0;    while(!q.empty()) {        int m = q.top();        vis[m] = true;        for(int i = 0 ; i < vc[m].size() ; i++) {            gg = vc[m][i];            if(dis[m] + gg.w < dis[gg.v]) {                dis[gg.v] = dis[m] + gg.w;                if(!vis[gg.v]) {                    vis[gg.v] = true;                    q.push(gg.v);                }            }        }        q.pop();    }}int main() {    int t;    TnT gg;    scanf("%d" , &t);    while(t--) {        scanf("%d%d" , &n , &m);        for(int i = 1 ; i <= n ; i++) {            vc[i].clear();            dis[i] = inf;        }        for(int i = 1 ; i <= m ; i++) {            scanf("%d%d%d" , &a[i] , &b[i] , &c[i]);            gg.v = b[i] , gg.w = c[i];            vc[a[i]].push_back(gg);        }        dij(1);        long long sum = 0;        for(int i = 1 ; i <= n ; i++) {            sum += (long long)dis[i];        }        for(int i = 1 ; i <= n ; i++) {            vc[i].clear();            dis[i] = inf;        }        for(int i = 1 ; i <= m ; i++) {            gg.v = a[i] , gg.w = c[i];            vc[b[i]].push_back(gg);        }        dij(1);        for(int i = 1 ; i <= n ; i++) {            sum += (long long)dis[i];        }        printf("%lld\n" , sum);    }    return 0;    }

poj 1511 Invitation Cards(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.