hdu 4628 Pieces 状压dp

题目链接

 

枚举所有状态, 1表示这个字符还在原来的串中, 0表示已经取出来了。

代码中j = (j+1)|i的用处是枚举所有包含i状态的状态。

#include <iostream>
#include <vector>
#include <cstdio>
#include <cstring>
#include <algorithm>
#include <cmath>
#include <map>
#include <set>
#include <string>
#include <queue>
#include <stack>
#include <bitset>
using namespace std;
#define pb(x) push_back(x)
#define ll long long
#define mk(x, y) make_pair(x, y)
#define lson l, m, rt<<1
#define mem(a) memset(a, 0, sizeof(a))
#define rson m+1, r, rt<<1|1
#define mem1(a) memset(a, -1, sizeof(a))
#define mem2(a) memset(a, 0x3f, sizeof(a))
#define rep(i, n, a) for(int i = a; i<n; i++)
#define fi first
#define se second
typedef pair<int, int> pll;
const double PI = acos(-1.0);
const double eps = 1e-8;
const int mod = 1e9+7;
const int inf = 1061109567;
const int dir[][2] = { {-1, 0}, {1, 0}, {0, -1}, {0, 1} };
int mark[1<<17], len, dp[1<<17];
string s;
int check(int x) {
    if(!x)
        return 1;
    int i = 0, j = len-1;
    while(i<j) {
        while(((1<<i)&x)==0)
            i++;
        while(((1<<j)&x)==0)
            j--;
        if(s[i]!=s[j])
            return 0;
        i++, j--;
    }
    return 1;
}
int main()
{
    int n;
    cin>>n;
    while(n--) {
        cin>>s;
        len = s.size();
        int sta = 1<<len;
        for(int i = 0; i<sta; i++) {
            mark[i] = check(i);
        }
        mem2(dp);
        dp[sta-1] = 0;
        for(int i = sta-2; i>=0; i--) {
            for(int j = i; j<sta; j = (j+1)|i) {
                if(!mark[i^j])
                    continue;
                if(dp[i]>dp[j]+1)
                    dp[i] = dp[j]+1;
            }
        }
        printf("%d\n", dp[0]);
    }
    return 0;
}

 

你可能感兴趣的:(hdu 4628 Pieces 状压dp)