题目链接: http://acm.nyist.net/JudgeOnline/problem.php?pid=115
dijkstra算法。
#include "stdio.h" #include "string.h" #define N 1005 #define INF 0x3fffffff bool vis[N]; int map[N][N]; bool mark[N]; int dist[N]; int dij(int start,int n) { int mint; int i,j,k; memset(mark,false,sizeof(mark)); mark[start] = true; for(i=1;i<=n; ++i) dist[i] = map[start][i]; for(i=2; i<=n; ++i) { k = -1; mint = INF; for(j=1; j<=n; ++j) { if(!mark[j] && mint>dist[j]) { mint = dist[j]; k = j; } } mark[k] = true; if(vis[k]) return dist[k]; for(j=1; j<=n; ++j) { if(!mark[j] && dist[j] > dist[k]+map[k][j]) dist[j] = dist[k]+map[k][j]; } } } int main() { int T; int i,j; int x,y,k; int n,m,p,start; scanf("%d",&T); while(T--) { memset(vis,false,sizeof(vis)); scanf("%d %d %d %d",&n,&m,&p,&start); for(i=0; i<n; ++i) { scanf("%d",&k); vis[k] = true; } for(i=1; i<=m; ++i) { for(j=1; j<=m; ++j) map[i][j]=INF; } while(p--) { scanf("%d %d %d",&x,&y,&k); if(k<map[x][y]) map[x][y]=map[y][x]=k; } printf("%d ",dij(start,m)); } return 0; } <strong> </strong>