#include<iostream>
#include<map>
#include<algorithm>
#include<vector>
using namespace std;
const int maxn = 210;
const int INF = 1 << 31 - 1;
int n, k;
string stCity;
int weight[maxn], w[maxn], d[maxn], num[maxn];
int cost[maxn][maxn], pre[maxn];
bool vis[maxn] = { false };
map<string, int> cityToInt;
map<int, string> intToCity;
vector<int> path;
void Dijkstra(int st) {
fill(d, d + maxn, INF);
d[st] = 0;
w[st] = 0;
num[st] = 1;
for(int i = 0; i < n; i++) {
int u = -1, MIN = INF;
for(int j = 0; j < n; j++) {
if(vis[j] == false && d[j] < MIN) {
u = j;
MIN = d[j];
}
}
if(u == -1) return;
vis[u] = true;
for(int v = 0; v < n; v++) {
if(vis[v] == false && cost[u][v] != INF) {
if(d[u] + cost[u][v] < d[v]) {
d[v] = d[u] + cost[u][v];
w[v] = w[u] + weight[v];
num[v] = num[u];
pre[v] = u;
} else if(d[u] + cost[u][v] == d[v]) {
if(w[u] + weight[v] > w[v]) {
w[v] = w[u] + weight[v];
pre[v] = u;
}
num[v] += num[u];
}
}
}
}
}
void print() { // 打印路径
for(int i=0;i<path.size();i++) {
if(i) cout << "->";
cout << intToCity[path[i]];
}
}
void DFS(int st) { // 记录路径, 同时可以由w[x] / path.size()-1 得到maxinum average happiness
if(st == 0) {
path.push_back(st);
return;
}
DFS(pre[st]);
path.push_back(st);
}
int main() {
cin >> n >> k >> stCity;
fill(cost[0], cost[0] + maxn * maxn, INF);
for(int i = 1; i <= n-1; i++) {
string temp;
cin >> temp >> weight[i];
cityToInt[temp] = i;
intToCity[i] = temp;
}
cityToInt[stCity] = 0;
intToCity[0] = stCity;
for(int i = 0; i < k; i++) {
string a, b;
int id1, id2;
cin >> a >> b;
id1 = cityToInt[a];
id2 = cityToInt[b];
cin >> cost[id1][id2];
cost[id2][id1] = cost[id1][id2];
}
Dijkstra(cityToInt[stCity]);
int dest = cityToInt["ROM"];
DFS(cityToInt["ROM"]);
cout << num[dest] << " " << d[dest] << " " << w[dest] << " " << w[dest] / (path.size() - 1) << endl;
print();
return 0;
}
PAT A1087(使用Dijkstra,容易理解系列)
于 2021-03-02 21:25:07 首次发布