起点有多个,处理方法就是再设置一个起点a作为真正的起点,然后a到那多个起点的距离设置成0,这样那多个起点被当做中间节点来处理,便可以直接使用dijkstra了
#include<iostream> #include<cstring> #include<cstdio> #define INF 0x3f3f3f3f using 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; }