Choose the best route(迪傑斯特拉)

來源:互聯網
上載者:User

標籤:style   blog   color   os   問題   代碼   

     通過做這題,發現了自己的問題很大,做題不是貼代碼,而是要瞭解思想;這題考的是有一個起點的集合,求起點集合到一個終點的最短距離,

本來想用Floy的但一看map[1000][1000]逾時,有向圖,逆序建鄰接矩陣,這樣就成了一個終點到所有點的最短路了。

 1 #include <stdio.h> 2 #include <string.h> 3 #include <stdlib.h> 4 #define N 1000001 5 int n,m,s,w; 6 int map[1001][1001]; 7 int v[1001],dis[1001]; 8 void DJ() 9 {10     memset(v,0,sizeof(v));11     for(int i=1;i<=n;i++)12         dis[i]=N;13     dis[s]=0;14     int min,k;15     for(int i=1;i<=n;i++)16     {17         min=N;18         for(int j=1;j<=n;j++)19         {20             if(v[j]==0&&min>dis[j])21             {22                 min=dis[j];23                 k=j;24             }25         }26             if(min==N) break;27             v[k]=1;28             for(int j=1;j<=n;j++)29             {30                 if(v[j]==0&&map[k][j]+dis[k]<dis[j])31                     dis[j]=dis[k]+map[k][j];32             }33 34     }35 }36 int main()37 {38     int x,y,z;39     while(scanf("%d%d%d",&n,&m,&s)!=EOF)40     {41         for(int i=1;i<=n;i++)42         {43             for(int j=1;j<=n;j++)44             {45                 map[i][j]=N;46             }47             map[i][i]=0;48         }49         while(m--)50         {51             scanf("%d%d%d",&x,&y,&z);52             if(map[y][x]>z)53             {54                 map[y][x]=z;55             }56         }57         DJ();58         scanf("%d",&w);59         int bb[1001];60         for(int i=0;i<w;i++)61         {62             scanf("%d",&bb[i]);63         }64         DJ();65 66         int min=N;67         for(int i=0;i<w;i++)68             if(dis[bb[i]]<min)69             min=dis[bb[i]];70 71             if(min==N)72                 printf("-1\n");73             else74         printf("%d\n",min);75     }76     return 0;77 }

 

聯繫我們

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