loj #161 子集卷积

求不相交集合并卷积

 

sol:

集合并卷积?看我 FWT!

交一发,10 以上的全 T 了

然后经过参考别人代码认真比对后发现我代码里有这么一句话:

rep(s, 0, MAXSTATE) rep(i, 0, n) rep(j, 0, n - i) h[i + j][s] = inc(h[i + j][s], mul(f[i][s], g[j][s]));

把它改成

rep(i, 0, n) rep(j, 0, n - i) rep(s, 0, MAXSTATE) h[i + j][s] = inc(h[i + j][s], mul(f[i][s], g[j][s]));

就过了...

有理有据地分析一波,上面那种写法会访问 $O(2^n)$ 次不连续的空间,下面那种写法只有 $O(n)$ 次

写出来主要还是提醒自己以后数组访问尽量连续吧...

orz

#include <bits/stdc++.h>
#define LL long long
#define rep(i, s, t) for (register int i = (s), i##end = (t); i <= i##end; ++i)
#define dwn(i, s, t) for (register int i = (s), i##end = (t); i >= i##end; --i)
using namespace std;
namespace IO{
    const int BS=(1<<23)+5; int Top=0;
    char Buffer[BS],OT[BS],*OS=OT,*HD,*TL,SS[20]; const char *fin=OT+BS-1;
    char Getchar(){if(HD==TL){TL=(HD=Buffer)+fread(Buffer,1,BS,stdin);} return (HD==TL)?EOF:*HD++;}
    void flush(){fwrite(OT,1,OS-OT,stdout);}
    void Putchar(char c){*OS++ =c;if(OS==fin)flush(),OS=OT;}
    void write(int x){
        if(!x){Putchar('0');return;} if(x<0) x=-x,Putchar('-');
        while(x) SS[++Top]=x%10,x/=10;
        while(Top) Putchar(SS[Top]+'0'),--Top;
    }
    int read(){
        int nm=0,fh=1; char cw=Getchar();
        for(;!isdigit(cw);cw=Getchar()) if(cw=='-') fh=-fh;
        for(;isdigit(cw);cw=Getchar()) nm=nm*10+(cw-'0');
        return nm*fh;
    }
}
using namespace IO;
const int mod = 1e9 + 9, maxn = (1 << 21);
int n;
int f[21][maxn], g[21][maxn], h[21][maxn], bt[maxn];
inline int inc(int x, int y) {
    x += y;
    if (x >= mod)
        x -= mod;
    return x;
}
inline int dec(int x, int y) {
    x -= y;
    if (x < 0)
        x += mod;
    return x;
}
inline int mul(int x, int y) { return 1LL * x * y % mod; }
void fwt(int *a, int n, int f) {
    for (int i = 1; i < n; i <<= 1) {
        for (int j = 0; j < n; j += (i << 1)) {
            for (int k = 0; k < i; k++) {
                int x = a[j + k], y = a[j + k + i];
                if (f == 1)
                    a[j + k + i] = inc(x, y);
                else
                    a[j + k + i] = dec(y, x);
            }
        }
    }
}
int main() {
    n = read();
    int MAXSTATE = (1 << n) - 1;
    rep(s, 0, MAXSTATE) bt[s] = __builtin_popcount(s);
    rep(s, 0, MAXSTATE) f[bt[s]][s] = read();
    rep(s, 0, MAXSTATE) g[bt[s]][s] = read();
    rep(s, 0, n) fwt(f[s], MAXSTATE + 1, 1), fwt(g[s], MAXSTATE + 1, 1);
    rep(i, 0, n) rep(j, 0, n - i) rep(s, 0, MAXSTATE) h[i + j][s] = inc(h[i + j][s], mul(f[i][s], g[j][s]));
    //rep(s, 0, MAXSTATE) rep(i, 0, n) rep(j, 0, n - i) h[i + j][s] = inc(h[i + j][s], mul(f[i][s], g[j][s]));
    rep(s, 0, n) fwt(h[s], MAXSTATE + 1, -1);
    rep(s, 0, MAXSTATE) write(h[bt[s]][s]), Putchar(' ');
    Putchar('\n'); flush();
}
View Code

 

posted @ 2019-03-27 10:50  探险家Mr.H  阅读(339)  评论(0编辑  收藏  举报