La Vie en rose
Time Limit: 7000/3500 MS (Java/Others) Memory Limit: 65536/65536 K (Java/Others)
Total Submission(s): 2156 Accepted Submission(s): 682
Problem Description
Professor Zhang would like to solve the multiple pattern matching problem, but he only has only one pattern string p=p1p2...pm. So, he wants to generate as many as possible pattern strings from p using the following method:
1. select some indices i1,i2,...,ik such that 1≤i1<i2<...<ik<|p| and |ij−ij+1|>1 for all 1≤j<k.
2. swap pij and pij+1 for all 1≤j≤k.
Now, for a given a string s=s1s2...sn, Professor Zhang wants to find all occurrences of all the generated patterns in s.
Input
There are multiple test cases. The first line of input contains an integer T, indicating the number of test cases. For each test case:
The first line contains two integers n and m (1≤n≤105,1≤m≤min{5000,n}) -- the length of s and p.
The second line contains the string s and the third line contains the string p. Both the strings consist of only lowercase English letters.
Output
For each test case, output a binary string of length n. The i-th character is "1" if and only if the substring sisi+1...si+m−1 is one of the generated patterns.
Sample Input
3 4 1 abac a 4 2 aaaa aa 9 3 abcbacacb abc
Sample Output
1010 1110 100100100
Author
zimpha
Source
2016 Multi-University Training Contest 2
【题意】给两个串,长度分别是n和m,用b串和a串的每个相对位置匹配,能够匹配对应位置为1,反之为0。
匹配规则:字串中,每个位置可以和相邻的位置交换一次,当a的子串可以和b完全相同时,为完全匹配。
【分析】
dp[i][j][3] 代表 a匹配到i位置,b匹配到j位置,0与前面交换,1不变,2与后面交换。
这里可以用bitset优化(因为状态都是bool表示的),把a串存到bitset中,然后使用滚动数组。
dp[x][1] = ((dp[1 - x][1] | dp[1 - x][0]) << 1) & str[b[i] - 'a'];
dp[x][0] = (dp[1 - x][2] << 1) & str[b[i-1]-'a'];
dp[x][2] = ((dp[1 - x][0] | dp[1 - x][1]) << 1) & str[b[i + 1]-'a'];
dp中存的是每个位所对应的当前的状态。
代码:
#include<iostream>
#include<cstdio>
#include<cstring>
#include<algorithm>
#include<cmath>
#include<map>
#include<set>
#include<vector>
#include<bitset>
#define F first
#define S second
#define mp make_pair
using namespace std;
typedef __int64 LL;
const int maxn = 1e5 + 10;
char a[maxn], b[maxn];
bitset <maxn> str[26];
bitset <maxn> dp[2][3];
int main()
{
int T, n, m;
scanf("%d", &T);
while(T--)
{
scanf("%d%d", &n, &m);
scanf("%s%s", a, b);
for(int i = 0; i < 26; i++) str[i].reset();
for(int i = 0; i < 2; i++)
for(int j = 0; j < 3; j++) dp[i][j].reset();
for(int i = 0; i < n; i++)
{
str[a[i]-'a'][i] = 1;
}
dp[0][1] = str[b[0] - 'a'];
if(0 < m - 1)
dp[0][2] = str[b[1]-'a'];
for(int i = 1; i < m; i++)
{
int x = (i & 1);
dp[x][1] = ((dp[1 - x][1] | dp[1 - x][0]) << 1) & str[b[i] - 'a'];
dp[x][0] = (dp[1 - x][2] << 1) & str[b[i-1]-'a'];
if(i < m - 1)
dp[x][2] = ((dp[1 - x][0] | dp[1 - x][1]) << 1) & str[b[i + 1]-'a'];
}
for(int i = 0; i < n; i++)
{
if(dp[(1 & (m - 1))][1][i + m - 1] || dp[(1 & (m - 1))][0][i + m - 1]&&i + m -1 < n)
{
printf("1");
}
else printf("0");
}
printf("\n");
}
return 0;
}