迪克斯(马克思)算法。。
#include <iostream> #include <cstring> #include <map> #include <string> using namespace std; int n; int places; map<string, int> m; int adj[2010][2010]; bool isVis[1000]; int lowCost[1000]; int main() { int cases; cin >> cases; string source, des; map<string, int>::iterator iter; int a, b; int len; while(cases--) { cin >> n; places = 0; m.clear(); memset(adj, -1, sizeof(adj)); memset(isVis, false, sizeof(isVis)); memset(lowCost, 0, sizeof(lowCost)); for(int i = 0; i < n; i++) { cin >> source >> des >> len; if((iter = m.find(source)) != m.end()) a = iter->second; else { a = places++; m.insert(make_pair(source, a)); } if((iter = m.find(des)) != m.end()) b = iter->second; else { b = places++; m.insert(make_pair(des, b)); } adj[a][b] = adj[b][a] = len; } cin >> source >> des; if(source == des) { cout << "0/n"; continue; } if((iter = m.find(source)) != m.end()) a = iter->second; else { cout << "-1/n"; continue; } if((iter = m.find(des)) != m.end()) b = iter->second; else { cout << "-1/n"; continue; } isVis[a] = true; for(int i = 0; i < places; i++) { lowCost[i] = adj[a][i]; } while(1) { int max = 100000000; int index = a; for(int i = 0; i < places; i++) { if(!isVis[i] && lowCost[i] != -1 && lowCost[i] < max) { max = lowCost[i]; index = i; } } if(index == b) { cout << lowCost[b] << endl; break; } if(index == a) { cout << "-1" << endl; break; } isVis[index] = true; for(int i = 0; i < places; i++) { if(!isVis[i] && adj[index][i] != -1) { if(lowCost[i] == -1 || lowCost[i] > adj[index][i] + lowCost[index]) { lowCost[i] = adj[index][i] + lowCost[index]; } } } } } return 0; }