斯坦纳树模板

出自lxw博客  https://blog.csdn.net/qq_30358129/article/details/94589381

给出n个点,然后给出m条双向边,边有边权。

再给出一个大小为k的点集,求使得点集联通的最小花费。 

时间复杂度O(n*3^k + cE*2^k),其中c为spfa常数。

#include <bits/stdc++.h>
#define rep(i, a, b) for(int i = (a); i <= (b); i++)
using namespace std;
const int N = 1050;
const int M = 1e6;
const int INF = 0x3f3f3f3f;
int n,m,k,dp[N][1<<10],tot,endSt,head[N];
bool vis[N][1<<10];
queue<int>q;
struct E{
    int v,w,nxt;
}edge[M];
void ae(int u,int v,int w) {
    edge[++tot] = (E){v,w,head[u]};
    head[u] = tot;
    edge[++tot] = (E){u,w,head[v]};
    head[v] = tot;
}
void spfa(int sta) {
    while(!q.empty()) {
        int u = q.front();
        q.pop();
        vis[u][sta] = 0;
        for(int i = head[u]; ~i; i = edge[i].nxt) {
            int v = edge[i].v;
            int w = edge[i].w;
            if(dp[v][sta]>dp[u][sta]+w) {
                dp[v][sta] = dp[u][sta]+w;
                if(vis[v][sta]) continue;
                vis[v][sta] = 1;
                q.push(v);
            }
        }
    }
}
void init() {
    tot = 0;
    memset(dp,0x3f,sizeof(dp));
    memset(head,-1,sizeof(head));
    memset(vis,0,sizeof(vis));
}
int main() {
    ios::sync_with_stdio(0);
    while(cin>>n>>m) {
        init();
        rep(i, 1, m) {
            int u,v,w;
            cin>>u>>v>>w;
            ae(u,v,w);
        }
        cin>>k;
        int sup; //为任意一个关键点
        rep(i, 1, k) {
            int x;
            cin>>x;
            sup = x;
            dp[x][1<<(i-1)] = 0;
        }
        endSt = 1<<k;
        rep(sta, 0, endSt-1) { 
            rep(i, 1, n) {
                for(int sub = (sta-1)&sta; sub; sub = (sub-1)&sta)
                    dp[i][sta] = min(dp[i][sta],dp[i][sub]+dp[i][sta-sub]);
                if(dp[i][sta]!=INF) q.push(i),vis[i][sta] = 1;
            }
            spfa(sta);
        }
 
        cout<<dp[sup][endSt-1]<<endl;
    }
    return 0;
}

 

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值