L3-011 直捣黄龙(Dijkstra模板)

和L2-001几乎一模一样。。。套模板完事

#include <iostream>
#include <cstring>
#include <unordered_map>
#include <vector>

using namespace std;

const int N = 210;
int n, m, S, T;
string s, t;
int e[N][N], dist[N], cnt[N];
int total[N]; // 总城市数
int w[N], sum[N];
int pre[N];
bool st[N];
string city[N];
unordered_map<string, int> mp;

void dijkstra()
{
    memset(dist, 0x3f, sizeof dist);
    dist[S] = 0, sum[S] = w[S], total[S] = 1, cnt[S] = 1;
    for(int i = 0; i < n - 1; i++)
    {
        int t = -1;
        for(int j = 1; j <= n; j++)
            if(!st[j] && (t == -1 || dist[t] > dist[j]))
                t = j;
        st[t] = true;
        for(int j = 1; j <= n; j++)
        {
            if(dist[j] > dist[t] + e[t][j])
            {
                dist[j] = dist[t] + e[t][j];
                cnt[j] = cnt[t];
                total[j] = total[t] + 1;
                sum[j] = sum[t] + w[j];
                pre[j] = t;
            }
            else if(dist[j] == dist[t] + e[t][j])
            {
                cnt[j] = cnt[j] + cnt[t];
                if(total[j] < total[t] + 1)
                {
                    total[j] = total[t] + 1;
                    sum[j] = sum[t] + w[j];
                    pre[j] = t;
                }
                else if(total[j] == total[t] + 1)
                {
                    if(sum[j] < sum[t] + w[j])
                    {
                        sum[j] = sum[t] + w[j];
                        pre[j] = t;
                    }
                }
            }
        }
    }
}

int main()
{
    memset(e, 0x3f, sizeof e);
    cin >> n >> m >>  s >> t;
    mp[s] = 1;
    city[1] = s;
    for(int i = 2; i <= n; i++)
    {
        string c;
        int x;
        cin >> c >> x;
        mp[c] = i;
        city[i] = c;
        w[i] = x;
    }
    S = mp[s] , T = mp[t];
    while(m --)
    {
        string ca, cb;
        int x;
        cin >> ca >> cb >> x;
        int a = mp[ca], b = mp[cb];
        e[a][b] = e[b][a] = x;
    }
    
    dijkstra();
    
    vector<int> ans;
    for(int i = T; i != 1; i = pre[i]) ans.push_back(i);
    cout << s;
    for(int i = ans.size() - 1; i >= 0; i--) cout << "->" << city[ans[i]];
    cout << endl << cnt[T] << ' ' << dist[T] << ' ' << sum[T] << endl;
}
  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值