【PAT甲级】1087 All Roads Lead to Rome(dijkstra单源最短路)

还是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;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值