求长度 ( 最短路 )

题目链接
在这里插入图片描述

#include<bits/stdc++.h>
#define LL long long
#define pii pair<int,int>
#define mem(a,b) memset(a,b,sizeof(a))
using namespace std;
const int maxn=1e5+5;
const int inf=0x3f3f3f3f;
const int MOD=1e9+7;

struct TMD{
    int to,next,w;
}edge[maxn<<1];
int cnt,head[maxn],n,m,s,p[15],t[15];
int dis[15][maxn];
bool vis[maxn];
void add(int from,int to,int w){
    edge[++cnt]={to,head[from],w};
    head[from]=cnt;
}
void dij_queue(int R,int root) {
    mem(vis, false);
    priority_queue<pii, vector<pii >, greater<pii > > q;
    q.push({0, root});
    dis[R][root] = 0;
    pii pp;
    while (!q.empty()) {
        pp = q.top();
        q.pop();
        for (int i = head[pp.second]; i; i = edge[i].next) {
            int to = edge[i].to, w = edge[i].w;
            if (dis[R][to] > dis[R][pp.second] + w) {
                dis[R][to] = dis[R][pp.second] + w;
                if (!vis[to]) {
                    q.push({dis[R][to], to});
                    vis[to] = true;
                }
            }
        }
    }
}

int main() {
    int T, u, v,w;
    scanf("%d", &T);
    while (T--) {
        mem(head, 0);
        cnt = 0;
        mem(dis, inf);
        scanf("%d%d", &n, &m);
        for (int i = 1; i <= m; i++) {
            scanf("%d%d%d", &u, &v, &w);
            add(u, v, w);
            add(v, u, w);
        }
        scanf("%d", &s);
        for (int i = 1; i <= s; i++) {
            t[i]=i;
            scanf("%d", &p[i]);
            dij_queue(i,p[i]);
        }
        LL ans = 1e18;
        do {
            LL tot = dis[t[1]][0];
            for (int i = 2; i <= s; i++) {
                tot += dis[t[i-1]][p[t[i]]];
            }
            tot += dis[t[s]][0];
            ans = min(ans, tot);
        } while (next_permutation(t + 1, t + s + 1));
        printf("%lld\n", ans);
    }
    return 0;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值