AcWing
  • 首页
  • 活动
  • 题库
  • 竞赛
  • 应用
  • 更多
    • 题解
    • 分享
    • 商店
    • 问答
  • 吐槽
  • 登录/注册

AcWing 1135. 新年好

作者: 作者的头像   慕明 ,  2022-04-08 17:00:41 ,  所有人可见 ,  阅读 56


0


先预处理从$1,a,b,c,d,e$为起点到其他点的单源最短路,暴力枚举所有路径$5!$种,通过查表方式计算路径最小值

#include<bits/stdc++.h>
using namespace std;
const int N = 5e4 + 5, M = 2e5 + 5;
int h[N], ne[M], e[M], w[M], idx;
int tar[6], dist[6][N], vis[N];
void add(int a, int b, int c) {
    e[idx] = b;
    ne[idx] = h[a];
    w[idx] = c;
    h[a] = idx++;
}
struct HeapNode {
    int id, val;
    bool operator < (const HeapNode& t) const {
        return val > t.val;
    }
};
void dijkstra(int s, int id) {
    memset(dist[id], 0x3f, sizeof(dist[id]));
    memset(vis, 0, sizeof(vis));
    dist[id][s] = 0;
    priority_queue<HeapNode> q;
    q.push({s, 0});
    while(!q.empty()) {
        auto node = q.top();
        q.pop();
        int t = node.id;
        if(vis[t]) continue;
        vis[t] = true;
        for(int i = h[t];i != -1;i = ne[i]) {
            int j = e[i];
            if(dist[id][j] > dist[id][t] + w[i]) {
                dist[id][j] = dist[id][t] + w[i];
                q.push({j, dist[id][j]});
            }
        }
    }
}
int main()
{
    ios::sync_with_stdio(0), cin.tie(0), cout.tie(0);
    int n, m;
    memset(h, -1, sizeof(h));
    cin >> n >> m;
    unordered_map<int, int> mp;
    tar[0] = 1;
    for(int i = 1;i <= 5;i++) cin >> tar[i], mp[tar[i]] = i;
    mp[1] = 0;
    for(int i = 0;i < m;i++) {
        int a, b, c;
        cin >> a >> b >> c;
        add(a, b, c);
        add(b, a, c);
    }
    for(int i = 0;i <= 5;i++) dijkstra(tar[i], mp[tar[i]]);
    sort(tar + 1, tar + 6);
    int ans = 0x3f3f3f3f;
    do {
        int sum = 0;
        for(int i = 0;i < 5;i++) {
            sum += dist[mp[tar[i]]][tar[i + 1]];
        }
        ans = min(sum ,ans);
    } while(next_permutation(tar + 1, tar + 6));
    cout << ans << "\n";
    return 0;
}

0 评论

你确定删除吗?
1024
x

© 2018-2023 AcWing 版权所有  |  京ICP备17053197号-1
用户协议  |  常见问题  |  联系我们
AcWing
请输入登录信息
更多登录方式: 微信图标 qq图标
请输入绑定的邮箱地址
请输入注册信息