标签:
1 #include <stdio.h> 2 #include <string.h> 3 #include <queue> 4 #define inf 0x3f3f3f3f 5 #define N 1000000 6 using namespace std; 7 int vis[200], dis[200], head[200]; 8 int n, cnt, k; 9 char s1[40], s2[40]; 10 char sta[200][40]; 11 struct note 12 { 13 int from, to, cost, next; 14 }edge[N]; 15 void add(int x, int y, int z) 16 { 17 note e = {x, y, z, head[x]}; 18 edge[cnt] = e; 19 head[x] = cnt++; 20 } 21 void spfa() 22 { 23 queue<int>q; 24 memset(vis, 0, sizeof(vis)); 25 memset(dis, inf, sizeof(dis)); 26 q.push(1); 27 vis[1] = 1; 28 dis[1] = 0; 29 while(!q.empty()) 30 { 31 int u = q.front(); 32 q.pop(); 33 vis[u] = 0; 34 for(int i = head[u]; i != -1; i = edge[i].next) 35 { 36 int v = edge[i].to; 37 if(dis[v] > dis[u] + edge[i].cost) 38 { 39 dis[v] = dis[u] + edge[i].cost; 40 if(!vis[v]) 41 { 42 vis[v] = 1; 43 q.push(v); 44 } 45 } 46 } 47 } 48 if(dis[2] == inf) 49 printf("-1\n"); 50 else 51 printf("%d\n", dis[2]); 52 } 53 int main() 54 { 55 int a, b, c; 56 while(~scanf("%d", &n), n != -1) 57 { 58 int flag; 59 k = 2, cnt = 0; 60 scanf("%s%s", sta[1], sta[2]); 61 memset(head, -1, sizeof(head)); 62 for(int i = 0; i < n; i++) 63 { 64 scanf("%s%s%d", s1, s2, &c); 65 flag = 1; 66 for(int i = 1; i <= k; i++) 67 { 68 if(strcmp(s1, sta[i]) == 0) 69 { 70 flag = 0; 71 a = i; 72 break; 73 } 74 } 75 if(flag) 76 { 77 strcpy(sta[++k], s1); 78 a = k; 79 } 80 flag = 1; 81 for(int i = 1; i <= k; i++) 82 { 83 if(strcmp(sta[i], s2) == 0) 84 { 85 b = i; 86 flag = 0; 87 break; 88 } 89 } 90 if(flag) 91 { 92 strcpy(sta[++k], s2); 93 b = k; 94 } 95 add(a, b, c); 96 add(b, a, c); 97 } 98 if(strcmp(sta[1], sta[2]) == 0) 99 { 100 printf("0\n"); 101 continue; 102 } 103 spfa(); 104 } 105 return 0; 106 }
标签:
原文地址:http://www.cnblogs.com/digulove/p/4747223.html