刚开始用spfa(久闻大名却一次都没用过)过不了,改dijkstra,wa了十几次后,心灰意冷。。1个小时后终于发现是判断起点与终点相同时,直接continue了,导致后面的数据没有完全输入...改正这个问题后spfa的代码也过了,哈哈
#include <iostream> #include <algorithm> #include <cstring> #include <vector> #include <string> #include <map> #include <queue> using namespace std; #ifndef ONLINE_JUDGE #include <fstream> ifstream fin("test.txt"); #define cin fin #endif struct edge{ int to,w; }; const int MAXN = 200,INF = 10000000; vector <edge> adjmap[MAXN]; bool inq[MAXN]; int d[MAXN],n; map <string, int> m; void SPFA() { int i,j; memset(inq,0,sizeof(inq)); queue <int> q; for(i = 1; i <= 155; ++i) d[i] = INF; d[1] = 0; inq[1] = 1; q.push(1); while(!q.empty()) { int t = q.front(); q.pop(); inq[t] = 0; for(i = 0; i < adjmap[t].size(); ++i) { int to = adjmap[t][i].to; if(d[t] < INF && d[to] > d[t] + adjmap[t][i].w) { d[to] = d[t] + adjmap[t][i].w; if(!inq[to]) { inq[to] = 1; q.push(to); } } } } } int main() { ios::sync_with_stdio(false); int i,t,num; string a,b; while(cin >> n) { if(n == -1) break; m.clear(); for(i = 0; i < MAXN; ++i) adjmap[i].clear(); cin >> a >> b; int ok = 1; if(a == b) { ok = 0; } m[a] = 1; m[b] = 2; num = 3; for(i = 0; i < n; ++i) { cin >> a >> b >> t; if(!m[a]) m[a] = num++; if(!m[b]) m[b] = num++; edge tem; tem.to = m[a]; tem.w = t; adjmap[m[b]].push_back(tem); tem.to = m[b]; adjmap[m[a]].push_back(tem); } if(!ok) { cout << 0 << endl; continue; } SPFA(); if(d[2]!=INF) cout << d[2] << endl; else cout << -1 << endl; } return 0; }