hdu2680 Choose the best route

來源:互聯網
上載者:User

起點有多個,處理方法就是再設定一個起點a作為真正的起點,然後a到那多個起點的距離設定成0,這樣那多個起點被當做中間節點來處理,便可以直接使用dijkstra了

#include<iostream>#include<cstring>#include<cstdio>#define INF 0x3f3f3f3fusing namespace std;int n,m,s;int dis[1005][1005],cost[1005];bool used[1005];void dijkstra(int v){    int i,j;    int mini,pos;    for(i=1;i<=n;i++){        used[i]=0;        cost[i]=dis[v][i];    }    used[v]=1;    cost[v]=0;    for(i=1;i<=n;i++){        mini=INF;        for(j=1;j<=n;j++)            if(!used[j]&&cost[j]<mini){                pos=j;                mini=cost[j];            }        if(mini==INF||pos==s) break;        used[pos]=1;        for(j=1;j<=n;j++)            if(!used[j]&&cost[j]>cost[pos]+dis[pos][j])                cost[j]=cost[pos]+dis[pos][j];    }    if(cost[s]>=INF)        printf("-1\n");    else        printf("%d\n",cost[s]);}int main(){    int from,to,road;    int w,bin;    while(scanf("%d%d%d",&n,&m,&s)!=EOF){        memset(dis,0x3f,sizeof(dis));        while(m--){            scanf("%d%d%d",&from,&to,&road);            if(dis[from][to]>road)                dis[from][to]=road;   //不要忘記消除重邊        }        scanf("%d",&w);        while(w--){            scanf("%d",&bin);            dis[0][bin]=0;        }        dijkstra(0);    }    return 0;}

聯繫我們

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