很久以前做过的题,那个时候不知道为什么总是RE,现在没什么问题了,不过题目还是挺坑的,套了个实际的背景我还以为是有向边+起点终点不相同,实际上是无向边+起点终点可以相同...
1 #include <iostream> 2 #include <cstring> 3 #include <string> 4 #include <queue> 5 #include <map> 6 using namespace std; 7 8 const int INF = 99999999; 9 const int N = 201; 10 const int M = 20000; 11 int head[N]; 12 int dist[N]; 13 bool visit[N]; 14 int n, m, e; 15 16 struct Edge 17 { 18 int v, next, w; 19 } edge[M]; 20 21 void addEdge( int u, int v, int w ) 22 { 23 edge[e].v = v; 24 edge[e].w = w; 25 edge[e].next = head[u]; 26 head[u] = e++; 27 } 28 29 void spfa( int s ) 30 { 31 for ( int i = 1; i <= n; i++ ) 32 { 33 dist[i] = INF; 34 visit[i] = false; 35 } 36 dist[s] = 0; 37 visit[s] = true; 38 int q[N], top = 0; 39 q[top] = s; 40 top = ( top + 1 ) % n; 41 for ( int i = 0; i != top; i = ( i + 1 ) % n ) 42 { 43 int u = q[i]; 44 visit[u] = false; 45 for ( int j = head[u]; j != -1; j = edge[j].next ) 46 { 47 int v = edge[j].v, w = edge[j].w; 48 if ( dist[v] > dist[u] + w ) 49 { 50 dist[v] = dist[u] + w; 51 if ( !visit[v] ) 52 { 53 q[top] = v; 54 top = ( top + 1 ) % n; 55 visit[v] = true; 56 } 57 } 58 } 59 } 60 } 61 62 map<string, int> mp; 63 string from, to; 64 65 int main () 66 { 67 while ( cin >> m, m != -1 ) 68 { 69 e = 0; 70 n = 1; 71 memset( head, -1, sizeof(head) ); 72 mp.clear(); 73 cin >> from >> to; 74 int src = mp[from] = n++, des = src; 75 if ( mp.count(to) == 0 ) 76 { 77 des = mp[to] = n++; 78 } 79 while ( m-- ) 80 { 81 int d; 82 cin >> from >> to >> d; 83 if ( mp.count(from) == 0 ) 84 { 85 mp[from] = n++; 86 } 87 if ( mp.count(to) == 0 ) 88 { 89 mp[to] = n++; 90 } 91 addEdge( mp[from], mp[to], d ); 92 addEdge( mp[to], mp[from], d ); 93 } 94 n--; 95 spfa(src); 96 if ( dist[des] == INF ) dist[des] = -1; 97 cout << dist[des] << endl; 98 } 99 return 0; 100 }
时间: 2024-11-02 20:45:21