单源最短路——新年好

新年好

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

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

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

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

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

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

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

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

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

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

数据范围
1 ≤ n ≤ 50000 1≤n≤50000 1n50000,
1 ≤ m ≤ 105 1≤m≤105 1m105,
1 < a , b , c , d , e ≤ n 1<a,b,c,d,e≤n 1<a,b,c,d,en,
1 ≤ x , y ≤ n 1≤x,y≤n 1x,yn,
1 ≤ t ≤ 100 1≤t≤100 1t100
输入样例:
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

题解:

这道题我们乘车的方案有5!种,所以我们先预处理一下个个点对的最小距离然后dfs跑一遍求所有方案中的最小值。

#include <iostream>
#include <cstring>
#include <cstdio>
#include <queue>
using namespace std;
const int N = 50005;
const int M = 200005; 
int q[10];
int head[N], nxt[M * 2], pnt[M * 2], w[M * 2], E;
int dist[10][N];
int n, m;
void add_edge(int a, int b, int c){
    pnt[E] = b;
    w[E] = c;
    nxt[E] = head[a];
    head[a] = E++;
}
void dij(int num, int s){
    int i, u, v;
    priority_queue<pair<int, int>, vector<pair<int, int> >, greater<pair<int, int> > > q;
    for(i = 1; i <= n; i++)
        dist[num][i] = (1 << 30);
    dist[num][s] = 0;
    q.push(make_pair(dist[num][s], s));
    pair<int, int> p;
    while(!q.empty()){
        p = q.top();
        q.pop();
        u = p.second;
        if(p.first > dist[num][u]) continue;
        for(i = head[u]; i != -1; i = nxt[i]){
            v = pnt[i];
            if(dist[num][v] > dist[num][u] + w[i]){
                dist[num][v] = dist[num][u] + w[i];
                q.push(make_pair(dist[num][v], v));
            }
        }
    }
}
int vis[10];
int ans = 0;
void dfs(int u, int num, int now, int l){
    if(now == 6){
        ans = min(ans, l);
        return;
    }
    int i, v;
    for(i = 2; i <= 6; i++){
        if(!vis[i]){
            vis[i] = 1;
            dfs(q[i], i, now + 1, l + dist[num][q[i]]);
            vis[i] = 0;
        }
    }
}
int main(){
    int i, a, b, c;
    scanf("%d%d", &n, &m);
    q[1] = 1;
    for(i = 2; i <= 6; i++)
        scanf("%d", &q[i]);
    E = 0;
    memset(head, -1, sizeof(head));
    for(i = 1; i <= m; i++){
        scanf("%d%d%d", &a, &b, &c);
        add_edge(a, b, c);
        add_edge(b, a, c); 
    }
    for(i = 1; i <= 6; i++)
        dij(i, q[i]);
    vis[1] = 1;
    ans = (1 << 30);
    dfs(q[1], 1, 1, 0);
    printf("%d\n", ans);
    return 0;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值