Grass
题目大意:给你T条路的图,和S个起点和D个终点,问从S个起点中某个起点,到D个
终点中的某个终点的最短路径是多少。
思路:遍历起点S和终点D,用Dijkstra算法求单源最短路径即可。
#include<iostream> #include<algorithm> #include<cstdio> #include<cstring> using namespace std; const int MAXN = 1010; int Map[MAXN][MAXN],Dist[MAXN]; bool vis[MAXN]; void Dijkstra(int N,int s) { for(int i = 1; i <= N; ++i) { if(i != s) Dist[i] = Map[s][i]; } Dist[s] = 0; vis[s] = true; for(int i = 1; i <= N-1; ++i) { int Min = 0xfffff0; int k = 0; for(int j = 1; j <= N; ++j) { if(!vis[j] && Dist[j] < Min) { Min = Dist[j]; k = j; } } if(k == 0) return; vis[k] = true; for(int j = 1; j <= N; ++j) { if(!vis[j] && Map[k][j] != 0xfffff0 && Dist[j] > Dist[k] + Map[k][j]) { Dist[j] = Dist[k] + Map[k][j]; } } } } int C1[MAXN],C2[MAXN]; int main() { int T,S,D,N,a,b,w; while(~scanf("%d%d%d",&T,&S,&D)) { for(int i = 1; i <= 1010; ++i) for(int j = 1; j <= 1010; ++j) Map[i][j] = 0xffffff0; memset(C1,0,sizeof(C1)); memset(C2,0,sizeof(C2)); N = 0; for(int i = 0; i < T; ++i) { scanf("%d%d%d",&a,&b,&w); N = max(N,a); N = max(N,b); if(Map[a][b] > w) Map[a][b] = Map[b][a] = w; } for(int i = 0; i < S; ++i) { scanf("%d",&C1[i]); } for(int i = 0; i < D; ++i) { scanf("%d",&C2[i]); } int Min = 0xffffff0; for(int i = 0; i < S; ++i) { memset(vis,false,sizeof(vis)); memset(Dist,0,sizeof(Dist)); Dijkstra(N,C1[i]); for(int j = 0; j < D; ++j) if(Dist[C2[j]] < Min) Min = Dist[C2[j]]; } printf("%d\n",Min); } return 0; }
原文:http://blog.csdn.net/lianai911/article/details/42345905