还是dijkstra的模板题,这道题比较烦的是城市名是string,建图的话得要用一个哈希表映射一下城市名和数字下标的关系,输出答案时又要一个哈希表将下表映射回城市名。
Tips:最短路数量最开始输出的一直是错误的结果,找了很久发现是dist相同时应该直接让cnt[j] += cnt[t],距离相同时显然路线数量要加,与点权和及点数无关。
#include <bits/stdc++.h>
using namespace std;
const int N = 510;
int n, m, S, T;
int e[N][N], w[N];
int dist[N], cost[N], cnt[N], sum[N]; // 道路成本、城市幸福感、路线数、总城市数
unordered_map<string, int> mp;
bool st[N];
int pre[N];
string hashCity[N];
void dijkstra()
{
memset(dist, 0x3f, sizeof dist);
dist[S] = 0, cost[S] = w[S], cnt[S] = 1;
for(int i = 0; i < n - 1; i ++)
{
int t = -1;
for(int j = 0; j < n; j++)
if(!st[j] && (t == -1 || dist[t] > dist[j]))
t = j;
st[t] = true;
for(int j = 0; j < n; j++)
{
if(dist[j] > dist[t] + e[t][j])
{
dist[j] = dist[t] + e[t][j];
pre[j] = t;
cost[j] = cost[t] + w[j];
cnt[j] = cnt[t];
sum[j] = sum[t] + 1;
}
else if(dist[j] == dist[t] + e[t][j])
{
cnt[j] += cnt[t];
if(cost[j] < cost[t] + w[j])
{
pre[j] = t;
cost[j] = cost[t] + w[j];
// cnt[j] += cnt[t];
sum[j] = sum[t] + 1;
}
else if(cost[j] == cost[t] + w[j])
{
// 平均幸福感更大 ==> 经过城市数更少
if(sum[j] > sum[t] + 1)
{
pre[j] = t;
// cnt[j] += cnt[t];
sum[j] = sum[t] + 1;
}
}
}
}
}
}
int main()
{
memset(e, 0x3f, sizeof e);
cin >> n >> m;
string s;
cin >> s;
mp[s] = 0, S = 0;
hashCity[S] = s;
for(int i = 1; i < n; i ++)
{
string city;
int happy;
cin >> city >> happy;
mp[city] = i;
w[i] = happy;
hashCity[i] = city;
}
T = mp["ROM"];
while(m --)
{
string a, b;
int c;
cin >> a >> b >> c;
int ia = mp[a], ib = mp[b];
e[ia][ib] = e[ib][ia] = c;
}
dijkstra();
cout << cnt[T] << ' ' << dist[T] << ' ' << cost[T] << ' ' << int(cost[T] / sum[T]) << endl;
vector<int> ans;
for(int i = T; i != S; i = pre[i]) ans.push_back(i);
cout << hashCity[S];
for(int i = ans.size() - 1; i >= 0; i--) cout << "->" << hashCity[ans[i]];
cout << endl;
}