题目链接:HDU Today
立即集训要開始,抓紧时间练练手,最短路的基础题,第一次用STL的map
题目非常水,可是错了N遍。手贱了。本题不优点理的就是把地名转化为数字
#include <iostream> #include <stdio.h> #include <stdlib.h> #include <string.h> #include <map> #define N 155 #define INF 1e7 using namespace std; int m[N][N],dis[N]; int vis[N]; int edge,n; int Djistra() { for(int i = 0;i<=edge;i++) { vis[i] = 0; dis[i] = m[1][i]; } vis[1] = 1; dis[1] = 0; int u,mi; for(int i = 1;i<=edge;i++) { u = 1; mi = INF; for(int j = 1;j<=edge;j++) { if(!vis[j] && dis[j]<mi) { u = j; mi = dis[j]; } } vis[u] = 1; for(int j = 1;j<=edge;j++) { if(!vis[j] && m[u][j] < INF && dis[u] + m[u][j] < dis[j]) { dis[j] = dis[u] + m[u][j]; } } } return dis[2]; } /*int Floyd() { for(int k=1;k<edge;k++) for(int i=1;i<edge;i++) { for(int j=1;j<edge;j++) if(m[i][j]>m[i][k]+m[k][j]) m[i][j]=m[i][k]+m[k][j]; } return m[1][2]; }*/ int main() { char s[32],e[32]; int w; map<string,int>ma; while(scanf("%d",&n)!=EOF) { if(n==-1) break; int st = 0; ma.clear(); scanf("%s%s",s,e); if(strcmp(s,e)==0) //这个地方别家continue,后台还没输数据呢 st = 1; for(int i = 0;i<N;i++) { for(int j = 0;j<N;j++) { if(i==j) m[i][j] = 0; else m[i][j] = INF; } } ma[s] = 1; ma[e] = 2; edge = 3; for(int i = 0;i<n;i++) { scanf("%s%s%d",s,e,&w); if(ma[s]==0) ma[s] = edge++; if(ma[e]==0) ma[e] = edge++; if(w < m[ma[s]][ma[e]]) { m[ma[s]][ma[e]] = w; m[ma[e]][ma[s]] = w; } } if(st==1) { printf("0 "); continue; } int sum = Djistra(); if(sum<INF) printf("%d ",sum); else printf("-1 "); } return 0; }
char str1[10005][40],str2[10005][40],str[10005][40]; int judge(char *p) { for(int i = 1;i<=f;++i) if(!strcmp(str[i],p)) return i; strcpy(str[++f],p); return f; } for(int i = 1;i<=n;++i) scanf("%s%s%d",str1[i],str2[i],&str3[i]); for(int i = 1;i<=n;++i) { int x = judge(str1[i]); int y = judge(str2[i]); map[x][y] = map[y][x] = str3[i]; }