[NOIP2017 提高组] 宝藏 状压DP

https://www.luogu.com.cn/problem/P3959

  • 分别枚举每一个起点,因为后来的选择不会影响到前面的选择,满足无后效性,同时局部最优可以扩展到全局最优,满足最优子结构性质,可以使用 D P DP DP,使用常规状态压缩办法,枚举接下来的每一个可能的位置,然后记录状态进行 d f s dfs dfs,同时需要记录当前经过的宝藏屋的数量,如果需要更新,则更新,同时继续搜索,最后取所有解的最小值
  • 这里图比较小,要用邻接矩阵,不要用链式前向星,边太多了,会超时
#include <iostream>
#include <cstring>
#include <algorithm>
#include <queue>
#include <stack>
#include <vector>
#include <cmath>
#include <cstdio>
#include <map>
#include <unordered_map>
using namespace std;
typedef long long ll;
const int MAXN = 2e5 + 100;
const int INF = 0x3f3f3f3f;
int edge[15][15];
int f[1 << 15];
int dis[15];
int n;
void dfs(int s){
    for(int i=1;i<=n;i++){
        if(s & (1 << (i - 1))){
            for(int j=1;j<=n;j++){
                if(edge[i][j] == INF || i == j) continue;
                if(f[s | (1 << (j - 1))] > f[s] + dis[i] * edge[i][j]){
                    int tmp = dis[j];
                    dis[j] = dis[i] + 1;
                    f[s | (1 << (j - 1))] = f[s] + dis[i] * edge[i][j];
                    dfs(s | (1 << (j - 1)));
                    dis[j] = tmp;
                }
            }
        }
    }
}
int main(){
    #ifdef LOCAL
        freopen("input.txt", "r", stdin);
        freopen("output.txt", "w", stdout);
    #endif
    ios::sync_with_stdio(false);
    int m, u, v, w;
    cin >> n >> m;
    memset(edge, 0x3f, sizeof edge);
    for(int i=1;i<=m;i++){
        cin >> u >> v >> w;
        edge[u][v] = edge[v][u] = min(edge[u][v], w);
    }
    int ans = INF;
    for(int i=1;i<=n;i++){
        memset(dis, 0x3f, sizeof dis);
        memset(f, 0x3f, sizeof f);
        dis[i] = 1;
        f[1 << (i - 1)] = 0;
        dfs(1 << (i - 1));
        ans = min(f[(1 << n) - 1], ans);
    }
    cout << ans;
    return 0;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

Clarence Liu

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

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

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

打赏作者

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

抵扣说明:

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

余额充值