会之前感觉 AC 代码毫无道理,会之后觉得这简直太妙了!
解法分析
一句话概括下题意:输出 的子串中字符集为 的极长串的数量,如果一个串不被任何其他符合要求的串覆盖则是极长的。
好的,题意已经清晰了。最初的想法肯定是每次暴力找极长子串,这样是 的,太慢了。看看离线怎么做,设 表示字符集为 时的极长子串数量。
考虑一段极长子串 ,特别关注 中每种字符在 出现的最后一个位置中最小的那个,称其为代表位置 。那么 中会出现所有在 中出现过的字符,且 在 中只出现一次,且 不在 中出现,且 和 是一一对应的。
于是可以枚举 ,设 为满足 的最小 ,那么 可以是 ,顺序遍历 ,如果 不在 中,则当前 对应了一个极长的字符集为 中字符的子串,答案 即可。
分析下时间复杂度:对于每种字符,都会遍历一遍 ,因此时间复杂度为 。
参考代码
还有些细节,比如 怎么处理,爆空间需要开 short,具体看代码。
#include <bits/stdc++.h>
#define ll long long
#define ld long double
#define pii pair<int, int>
#define pll pair<ll, ll>
#define pushf push_front
#define pushb push_back
#define popf pop_front
#define popb pop_back
#define lowbit(x) (x-(x&(x-1)))
using namespace std;
int n, m, msk[10010], ans[10010];
short id[(1 << 26) + 10];
string s, C[10010];
int main(){
ios::sync_with_stdio(false);
cin >> s >> m;
for (int i = 1; i <= m; i++)
cin >> C[i];
for (int i = 1; i <= m; i++){
for (int j = 0; j < C[i].size(); j++)
msk[i] |= (1 << (C[i][j] - 'a'));
id[msk[i]] = i;
}
n = s.size(), s = ' ' + s;
for (int i = 1; i <= n; i++){//指定i为代表位
int S = 0;
for (int j = i; j <= n; j++){//此时[i,j]的字符集就代表了整串的字符集
if (i != j && s[j] == s[i])
break;
S |= (1 << (s[j] - 'a'));
if (j == n || !((S >> (s[j + 1] - 'a')) & 1))
ans[id[S]]++;
}
}
for (int i = 1; i <= m; i++)
cout << ans[id[msk[i]]] << "\n";
return 0;
}