1135. 新年好

重庆城里有 n 个车站,m 条 双向 公路连接其中的某些车站。

每两个车站最多用一条公路连接,从任何一个车站出发都可以经过一条或者多条公路到达其他车站,但不同的路径需要花费的时间可能不同。

在一条路径上花费的时间等于路径上所有公路需要的时间之和。

佳佳的家在车站 1,他有五个亲戚,分别住在车站 a,b,c,d,e。

过年了,他需要从自己的家出发,拜访每个亲戚(顺序任意),给他们送去节日的祝福。

怎样走,才需要最少的时间?

输入格式

第一行:包含两个整数 n,m,分别表示车站数目和公路数目。

第二行:包含五个整数 a,b,c,d,e,分别表示五个亲戚所在车站编号。

以下 m 行,每行三个整数 x,y,t,表示公路连接的两个车站编号和时间。

输出格式

输出仅一行,包含一个整数 T,表示最少的总时间。

数据范围

1≤n≤50000,
1≤m≤105,
1<a,b,c,d,e≤n,
1≤x,y≤n,
1≤t≤100

输入样例:
6 6
2 3 4 5 6
1 2 8
2 3 3
3 4 4
4 5 5
5 6 2
1 6 7
输出样例:
21
代码:
//预处理,求六遍dijkstra,处理出1,a,b,c,d,e到图中各点的单源最短路。
//然后枚举所有从1出发的方案,比如1->a->c->d->b->e就是其中之一,将这些方案的路径和求个最小值
#include <bits/stdc++.h>
using namespace std;

typedef pair<int, int> PII;

const int N = 50010, M = 200010, INF = 0x3f3f3f3f;

int n, m;
int h[N], e[M], w[M], ne[M], idx;
int dist[6][N]; // 6个最短单源路径
int source[6];  // 6个点
bool st[N];
int res = INF;
void add(int a, int b, int c)
{
    e[idx] = b;
    w[idx] = c;
    ne[idx] = h[a];
    h[a] = idx++;
}

void dijkstra(int start, int dist[])
{
    memset(dist, 0x3f, 4 * N); // 不能是sizeof(dist) 会全部初始化
    memset(st, 0, sizeof(st));

    dist[start] = 0;
    priority_queue<PII, vector<PII>, greater<PII>> heap;
    heap.push({0, start});

    while (heap.size())
    {
        PII t = heap.top();
        heap.pop();

        int ver = t.second, distance = t.first;
        if (st[ver])
            continue;
        st[ver] = 1;

        for (int i = h[ver]; i != -1; i = ne[i])
        {
            int j = e[i];
            if (!st[j] && dist[j] > dist[ver] + w[i])
            {
                dist[j] = dist[ver] + w[i];
                heap.push({dist[j], j});
            }
        }
    }
}

void dfs(int u, int start, int distance) // start用来确定用哪一个dist[start]
{
    if (u == 6)
    {
        res = min(res, distance);
        return;
    }

    for (int i = 1; i <= 5; i++)
    {
        if (!st[i])
        {
            int next = source[i];
            st[i] = 1;
            dfs(u + 1, i, distance + dist[start][next]);
            st[i] = 0;
        }
    }
}

int main()
{
    cin >> n >> m;
    source[0] = 1;
    for (int i = 1; i <= 5; i++)
        cin >> source[i];

    memset(h, -1, sizeof(h));

    while (m--)
    {
        int a, b, c;
        cin >> a >> b >> c;
        add(a, b, c), add(b, a, c);
    }

    for (int i = 0; i < 6; i++)
        dijkstra(source[i], dist[i]);

    memset(st, 0, sizeof(st));
    dfs(1, 0, 0);

    cout << res << endl;

    return 0;
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

追寻远方的人

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值