HDU 5745 dp, bitset优化

来源:互联网 发布:中国真实gdp季度数据 编辑:程序博客网 时间:2024/06/05 17:31

题目链接:见这里

题意:

N≤105的母串,M≤5000的模式串
对于模式串,不相邻的2个字符可以和相邻的交换
即abcd,ab换和cd也可以换,但bc换了cd就不能换了
求每个位置是否能匹配模式串

解题思路:

f[i][j][3]:=母串匹配到i,模式串匹配到j,0和前面换,1正好匹配,2和后面换
转移:f[i][j][0]=f[i−1][j−1][2],si=tj−1
f[i][j][1]=f[i−1][j−1][0] | f[i−1][j−1][1],si=tj
f[i][j][2]=f[i−1][j−1][0] | f[i−1][j−1][1],si=tj+1
由于dp维护的都是bool,且只从i−1转移过来
所以我们可以预处理母串字符集在母串中的位置到bitset中
对于每次转移只要左移一次并且与上匹配的模式串的字符的状态就好
即整体转移母串所有字符,左移一次相当于对上了当前状态的位置
时间复杂度为O(nm/64),bitset标准库里压ULL
事实上搞模式串的状态也是可以的

代码如下:

#include <bits/stdc++.h>using namespace std;const int N = 1e5+10;typedef bitset <N> Sta;int n, m;char s[N], t[N];Sta f[2][3], g[26]; //bitset 压缩第一维, 滚动第2维int main(){    int T;    scanf("%d", &T);    while(T--){        scanf("%d%d", &n, &m);        scanf("%s%s", s+1, t+1);        for(int i = 0; i < 26; i++) g[i].reset();        for(int i = 1; i <= n; i++) g[s[i]-'a'][i] = 1;        int cur = 0;        for(int i = 0; i < 3; i++) f[cur][i].reset();        f[cur][1].set(); //f[cur][0][1] = 1        for(int i = 1; i <= m; i++){            int pre = t[i - 1] - 'a', now = t[i] - 'a', nxt = t[i+1] - 'a';            if(i > 1) f[!cur][0] = (f[cur][2] << 1) & g[pre];            else f[!cur][0].reset();            f[!cur][1] = (f[cur][0] | f[cur][1]) << 1 & g[now];            if(i < m) f[!cur][2] = (f[cur][0] | f[cur][1]) << 1 & g[nxt];            else f[!cur][2].reset();            cur = !cur;        }        for(int i = 1; i <= n - m + 1; i++){            bool ans = f[cur][0][i + m - 1] | f[cur][1][i + m - 1];            putchar("01"[ans]);        }        for(int i = n - m + 2; i <= n; i++) putchar('0');        putchar('\n');    }    return 0;}
0 0
原创粉丝点击