牛客每日一题 和与或 数位dp+状态压缩

原题链接:https://ac.nowcoder.com/acm/problem/21336

目录

  • 题意
  • 分析
  • Code

题意

a [ i ] ∈ [ 0 , R [ i ] ] a[i]∈[0,R[i]] a[i][0,R[i]]
问 满 足 a [ 0 ] + a [ 1 ] + . . . a [ n ] = a [ 0 ] ∣ a [ 1 ] ∣ . . a [ n ] , 有 多 少 组 a 问满足a[0]+a[1]+...a[n]=a[0]|a[1]|..a[n],有多少组a a[0]+a[1]+...a[n]=a[0]a[1]..a[n]a

分析

根据加法和或运算的性质,我们发现在二进制下,每一位只能有一个1。很容易联想到数位dp。

然后写出状态 d p [ p o s ] [ l i m i t 1 ] [ l i m i t 2 ] . . [ l i m i t n ] dp[pos][limit1][limit2]..[limitn] dp[pos][limit1][limit2]..[limitn]如果直接这样写会比较麻烦,我们采用更优美的状态压缩去代替n个状态 d p [ p o s ] [ l i m i t ] = d p [ p o s ] [ 00...0 ] dp[pos][limit]=dp[pos][00...0] dp[pos][limit]=dp[pos][00...0]

然后就是上下界限制的判断问题,我们定一个state和limit,state代表当前所有R[i]在pos位的状态,limit表示当前pos位的状态,接下来分类讨论一下

  1. limit & (1<
  2. limit & (1<

Code

#include 
#include 
#include 
using namespace std;
#define fi first
#define se second
#define re register
typedef long long ll;
typedef pair<ll, ll> PII;
typedef unsigned long long ull;
const int N = 1e6 + 20, M = 1e6 + 5, INF = 0x3f3f3f3f;
const int MOD = 1e9+9;
ll a[N], bit[63], n;
ll dp[65][1<<11];
ll dfs(int pos, int limit) {
     
    if (pos == -1) return 1;
    if (dp[pos][limit] != -1) return dp[pos][limit];
    int state = 0;
    ll ans = 0;
    for (int i = 1; i <= n; i++) {
     
        if (a[i] & (1ll<<pos)) state |= (1<<i);
    }
    ans += dfs(pos-1, limit | state);
    for (int i = 1; i <= n; i++) {
     
        if (limit & (1<<i)) {
     
            ans += dfs(pos-1, state | limit);
        } else if (state & (1<<i)) {
     
            ans += dfs(pos-1, (state|limit) ^ (1<<i));
        }
    }
    return dp[pos][limit] = ans % MOD;
}

void solve() {
     
    cin >> n;
    for (int i = 1; i <= n; i++) cin >> a[i];
    memset(dp, -1, sizeof dp);
    cout << dfs(61, 0) << endl;
}

signed main() {
     
    ios::sync_with_stdio(0);
    cin.tie(0);
    cout.tie(0);
#ifdef ACM_LOCAL
    freopen("input", "r", stdin);
    freopen("output", "w", stdout);
#endif
    solve();
}

你可能感兴趣的:(动态规划)