1087 All Roads Lead to Rome (30 分)
思路有空更新
#include <iostream>
#include <cstring>
#include <map>
using namespace std;
const int inf = 0x3f3f3f3f;
int e[250][250], vis[250], dis[250], path[250], ret[250], cnt[250], a[250], aa[250];
double avg[250];
map<string, int> m;
map<int, string> m1;
int n, M, d, x;
void dijkstra(int s){
memset(dis, inf, sizeof dis);
dis[s] = 0;
ret[s] = 1;
for(int i = 0; i < n; ++i){
int t = -1;
for(int j = 1; j <= n; ++j)
if(!vis[j] && (t == -1 || dis[j] < dis[t]))
t = j;
vis[t] = 1;
for(int j = 1; j <= n; ++j) {
if(!vis[j] && dis[j] > dis[t] + e[t][j]) {
dis[j] = dis[t] + e[t][j];
aa[j] = aa[t] + a[j];
ret[j] = ret[t];
cnt[j] = cnt[t] + 1;
avg[j] = aa[j] * 1.0 / cnt[j];
path[j] = t;
}
else if(!vis[j] && dis[j] == dis[t] + e[t][j]) {
ret[j] += ret[t];
if(aa[j] < aa[t] + a[j]){
aa[j] = aa[t] + a[j];
cnt[j] = cnt[t] + 1;
avg[j] = aa[j] * 1.0 / cnt[j];
path[j] = t;
}
else if(aa[j] == aa[t] + a[j] && aa[j] * 1.0 / (cnt[t] + 1) > avg[j]){
cnt[j] = cnt[t] + 1;
avg[j] = aa[j] * 1.0 / cnt[j];
path[j] = t;
}
}
}
}
}
void dfs(int x) {
if(x == 1){
cout << m1[x];
return;
}
dfs(path[x]);
cout << "->" << m1[x];
}
int main() {
string s1, s2;
cin >> n >> M >> s1;
memset(e, inf, sizeof e);
for(int i = 1; i <= n; ++i)
e[i][i] = 0;
m[s1] = 1;
m1[1] = s1;
for(int i = 2; i <= n; ++i){
cin >> s1 >> a[i];
m[s1] = i;
m1[i] = s1;
if(s1 == "ROM") d = i;
}
while(M--) {
cin >> s1 >> s2 >> x;
e[m[s1]][m[s2]] = e[m[s2]][m[s1]] = x;
}
dijkstra(1);
printf("%d %d %d %d\n", ret[d], dis[d], aa[d], int(avg[d]));
dfs(d);
}