Dijkstra最短路 (反向做+去重邊)HDU
阿新 • • 發佈:2018-12-22
#include<stdio.h> #include<string.h> #define N 1500 #define INF 0x3f3f3f int n,t,f; int map[N][N]; int s[N]; int book[N]; int d[N]; void Dijkstra(int x) { int i,j; memset(book,0,sizeof(book)); book[x]=1;//終端 for(i=1; i<=n; i++) { d[i]=map[x][i]; } d[x]=0; //初始化; for(i=1; i<=n; i++) { int index=-1; int max=INF; for(j=1; j<=n; j++) { if(book[j]==0&&d[j]<max) { max=d[j]; index=j; } } if(index==-1) break; book[index]=1; for(j=1; j<=n; j++) { if(book[j]==0&&d[j]>map[index][j]+max) { d[j]=map[index][j]+max; } } } int max=INF; for(int k=1; k<=f; k++) { if(max>d[s[k]]) max=d[s[k]]; } //printf("%d ",d[i]); //printf("\n"); if(max>=INF) printf("-1\n"); else printf("%d\n",max); } int main() { int i,j,k,m,u,v,w; while(scanf("%d%d%d",&n,&m,&t)!=EOF) { memset(map,INF,sizeof(map)); for(i=0; i<m; i++) { scanf("%d%d%d",&u,&v,&w); if(w<map[v][u]) { map[v][u]=w;//倒著處理; } } scanf("%d",&f); for(i=1; i<=f; i++) { scanf("%d",&s[i]); } Dijkstra(t); } return 0; }