UVA11795-Mega Man's Mission(状压dp)

本文介绍了一种使用状态压缩动态规划(状压DP)的方法来解决一个涉及机器人战斗的问题。通过定义状态d[i][s]表示已消灭i个机器人且消灭过机器人的状态为s的总方案数,利用转移方程实现高效求解。文中详细阐述了预处理、状态定义、边界条件及最终目标,提供完整代码示例。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

题目链接

http://acm.hust.edu.cn/vjudge/problem/31961

思路

题目中n最大到16,因此考虑状压dp
定义状态d[i][s]:当前已经消灭了i个机器人,并且消灭过的机器人的状态为s的总方案数
转移方程:d[i][s] = sum(d[i - 1][ps]); 其中s和ps只有一位不同,并且s中1的个数比ps中1的个数多1
边界:d[0][0] = 0
目标:d[n][(1 << n) - 1]

细节

  1. 可先预处理出选出的机器人集合能够消灭的其他机器人
  2. 注意不要忘记root机器人的武器

代码

#include <iostream>
#include <cstring>
#include <stack>
#include <vector>
#include <set>
#include <map>
#include <cmath>
#include <queue>
#include <sstream>
#include <iomanip>
#include <fstream>
#include <cstdio>
#include <cstdlib>
#include <climits>
#include <deque>
#include <bitset>
#include <algorithm>
using namespace std;

#define PI acos(-1.0)
#define LL long long
#define PII pair<int, int>
#define PLL pair<LL, LL>
#define mp make_pair
#define IN freopen("in.txt", "r", stdin)
#define OUT freopen("out.txt", "wb", stdout)
#define scan(x) scanf("%d", &x)
#define scan2(x, y) scanf("%d%d", &x, &y)
#define scan3(x, y, z) scanf("%d%d%d", &x, &y, &z)
#define sqr(x) (x) * (x)
#define pr(x) cout << #x << " = " << x << endl
#define lc o << 1
#define rc o << 1 | 1
#define pl() cout << endl
#define CLR(a, x) memset(a, x, sizeof(a))
#define FILL(a, n, x) for (int i = 0; i < n; i++) a[i] = x

const int maxn = 17;
int ab[maxn], root, c[1 << maxn];
LL d[maxn][1 << maxn];
int n, num[1 << maxn];
char s[maxn];

void init() {
    memset(c, 0, sizeof(c));
    int ALL = 1 << n;
    for (int s = 0; s < ALL; s++) {
        num[s] = __builtin_popcount(s);
        for (int i = 1; i <= n; i++) {
            if (s & (1 << (i - 1))) c[s] |= ab[i];
        }
    }
    c[0] = root;
}

LL dp() {
    CLR(d, 0);
    d[0][0] = 1;
    int ALL = 1 << n;
    for (int i = 1; i <= n; i++) {
        for (int s = 0; s < ALL; s++) {
            for (int k = 0; k < n; k++) {
                if ((s & (1 << k)) == 0) continue;
                int ps = s ^ (1 << k);
                if (((c[ps] & (1 << k)) == 0) && (c[0] & (1 << k)) == 0) continue;
                d[i][s] += d[i - 1][ps];
            }
        }
    }
    return d[n][ALL - 1];
}

int main() {
    int T, kase = 0;
    scan(T);
    while (T--) {
        scan(n);
        memset(s, '\0', sizeof(s));
        scanf("%s", s);
        root = 0;
        for (int i = 0; i < n; i++) root += ((s[i] - '0') << i);
        for (int i = 1; i <= n; i++) {
            scanf("%s", &s);
            ab[i] = 0;
            for (int j = 0; j < n; j++) ab[i] += ((s[j] - '0') << j);
        }
        init();
        LL ans = dp();
        printf("Case %d: %lld\n", ++kase, ans);
    }
    return 0;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值