1. 程式人生 > >HDU 4906 Our happy ending (狀壓DP)

HDU 4906 Our happy ending (狀壓DP)

中一 article san mar break std 多少 滾動 con

HDU 4906 Our happy ending

pid=4906" style="">題目鏈接

題意:給定n個數字,每一個數字能夠是0-l,要選當中一些數字。然後使得和為k,問方案

思路:狀壓dp。滾動數組,狀態表示第i個數字。能組成的數字狀態為s的狀態,然後每次一個數字,循環枚舉它要選取1 - min(l,k)的多少,然後進行狀態轉移

代碼:

#include <cstdio>
#include <cstring>

typedef long long ll;

const int N = (1<<20) + 5;
const ll MOD = 1000000007;
int t, n, k;
ll l, dp[N];

int main() {
    scanf("%d", &t);
    while (t--) {
	scanf("%d%d%lld", &n, &k, &l);
	int s = (1<<k);
	if (l > k) {
	    ll yu = l - k;
	    l = k;
	}
	memset(dp, 0, sizeof(dp));
	dp[0] = 1;
	while (n--) {
	    for (int i = s - 1; i >= 0; i--) {
		if (dp[i] == 0) continue;
		ll tmp = yu * dp[i] % MOD;
		ll now = dp[i];
		for (int j = 1; j <= l; j++) {
		    int next = i|((i<<j)&(s - 1)|(1<<(j - 1)));
		    dp[next] = (dp[next] + now) % MOD;
		}
		dp[i] = (dp[i] + tmp) % MOD;
	    }
	}
	ll ans = 0;
	for (int i = 0; i < s; i++) {
	    if (i&(1<<(k - 1))) {
		ans = (ans + dp[i]) % MOD;
	    }
	}
	printf("%lld\n", ans);
    }
    return 0;
}


HDU 4906 Our happy ending (狀壓DP)