这是一道简单的最短路问题,但这道题的坑点是用number代表string,自然用map<string, int>;值得注意的是: map初始化都为0,导致端点不能用0表示!然后是多组数据测试中,map不需要初始化!
#include<cstdio> #include<algorithm> #include<cstring> #include<map> #include<string> using namespace std; int dis[205][205]; map<string, int> G; char from[10005]; char to[10005]; int n; void init(){ for(int i = 1; i <= n; i++){ for(int j = 1; j <= n; j++){ dis[i][j] = 0; } } } int floyd(int x,int y){ for(int k = 1; k <= n; k++){ for(int i = 1; i <= n; i++){ for(int j = 1; j <= n; j++){ if(dis[i][k] > dis[i][j] && dis[k][j] > dis[i][j]){ dis[i][j] = min(dis[i][k], dis[k][j]); } } } } printf("%d tons\n\n",dis[x][y]); } int main(){ int m,cas = 0; while(~scanf("%d%d",&n,&m)){ if(n == 0 && m == 0) break; init(); int cnt = 1; for(int i = 0; i < m; i++){ int d; scanf("%s%s%d",from,to,&d); if(G[from] == 0) G[from] = cnt++; if(G[to] == 0) G[to] = cnt++; dis[G[from]][G[to]] = d; dis[G[to]][G[from]] = d; } scanf("%s%s",from,to); int x = G[from]; int y = G[to]; printf("Scenario #%d\n",++cas); floyd(x,y); } return 0; }