1. 程式人生 > >SPOJTLE - Time Limit Exceeded(高位字首和)

SPOJTLE - Time Limit Exceeded(高位字首和)

題意

題目連結

題目的意思是給一個數組C,長度為n,每個數字的範圍是2^m,然後要求構造一個數組a,滿足

1、a[i] % C[i] !=0 ;

2、a[i] < 2^m ;

3、a[i] & a[i+1] = 0;

Sol

直接dp的話就是先列舉補集的子集,這樣的複雜度是\(3^n\)

然後補集的子集可以用高位字首和優化一下

時間複雜度:\(O(2^n * n)\)

#include<cstdio>
#include<cstring>
using namespace std;
const int MAXN = 1e5 + 10, mod = 1000000000;
inline int read() {
    char c = getchar(); int x = 0, f = 1;
    while(c < '0' || c > '9') {if(c == '-') f = -1; c = getchar();}
    while(c >= '0' && c <= '9') x = x * 10 + c - '0', c = getchar();
    return x * f;
}
int N, M, a[MAXN], c[MAXN], f[51][65537], sum[51][65537];
int add(int &x, int y) {
    x = (x + y >= mod ? x + y - mod : x + y);
}
int solve() {
    N = read(); M = read(); int Lim = (1 << M) - 1;
    memset(f, 0, sizeof(f));
    memset(sum, 0, sizeof(sum));
    f[0][0] = 1;
    for(int i = 0; i <= Lim; i++) sum[0][i] = 1;
    for(int i = 1; i <= N; i++) {
        c[i] = read();
        for(int sta = 1; sta <= Lim; sta ++) {
            if(!(sta % c[i])) continue;
            int s = (~sta) & Lim;
            sum[i][sta] = f[i][sta] = sum[i - 1][s];
        }
        for(int j = 0; j < M; j++)//必須先列舉這個 
            for(int sta = 0; sta <= Lim; sta++)
                if(sta & (1 << j)) add(sum[i][sta], sum[i][sta ^ (1 << j)]);
    }
    int ans = 0;
    for(int i = 0; i <= Lim; i++) add(ans, f[N][i]);
    return ans;
}
int main() {
    int T = read();
    while(T--) printf("%d\n", solve());
    return 0;
}