洛谷 2622 关灯问题Ⅱ

本文深入探讨了状压动态规划(DP)算法的实现细节,通过一个具体的编程问题,展示了如何利用状压技术优化DP算法,减少状态空间,提高算法效率。文章提供了完整的代码示例,包括输入读取、状态转移和最优解的计算过程。

状压DP练习题

#include <algorithm>
#include <iostream>
#include <cstring>
#include <cstdio>
#include <cctype>
#include <cmath>

inline void read(int & x)
{
    int k = 1; x = 0;
    char c = getchar();
    while (!isdigit(c)) 
        if (c == '-') c = getchar(), k = -1;
        else c = getchar();
    while (isdigit(c))
        x = (x << 3) + (x << 1) + (c ^ 48),
        c = getchar();
    x *= k;
}

int n, m, x, cnt = 0, y, s = 1, u;
int a[110][12], tot = 0, f[50505], d[50505], v[50505], dp[50550];

signed main()
{
    read(n), read(m);
    for (int i = 1; i <= m; ++i)
        for (int j = 1; j <= n; ++j)
            read(a[i][j]);
    for (int i = 0; i <= 50505; ++i) dp[i] = 1199887766;
    dp[(1 << n) - 1] = 0;
    for (int i = (1 << n) - 1; i >= 0; --i)
    {
        for (int j = 1; j <= m; ++j)
        {
            int newnode = i;
            for (int q = 1; q <= n; ++q)
            {
                if (a[j][q] == 0) continue;
                if (!((1 << (q - 1)) & i) && a[j][q] == -1) newnode ^= (1 << (q - 1));
                if (((1 << (q - 1)) & i) && a[j][q] == 1) newnode ^= (1 << (q - 1));
            }
            dp[newnode] = std::min(dp[newnode], dp[i] + 1); 
        }
    }
    printf("%d", dp[0] == 1199887766 ? -1 : dp[0]);
    return 0;
}

 

转载于:https://www.cnblogs.com/yanyiming10243247/p/9989700.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值