http://acm.hdu.edu.cn/showproblem.php?pid=4821
题意:
给一个字符串S,和2个数L,M。 s'len<=1e5
问你有多少个的子串满足 如下条件:
1、串长为M*L
2、能由M个 【长度为L】的 【不完全相同】的 【S的子串】 构成 (*)
(一个子串A与子串B的起始位置不同,即认为他们分别是2个子串,即答案数+2,与(*)中的【不完全相同】不一样)
暴力思路很简单,就是先预处理S,把每个长度为L的子串都hash成ull,然后遍历其每一个长度为M*L的子串看是否符合条件2即可。若符合,则答案数加1。
稍稍改进下就是,不用暴力匹配每一个长度为M*L的子串,只需要每次滑动L长度,维护一个M*L的串即可。
这里的基本单位是【每个长度为L的子串 hash成的一个ull数】
因此检测一个M*L串时,需要从某个地方开始,然后把在i,i+l,i+l+l,i+l+l+l....里滑动维护M*L的串
由于串长为L,最多需要从L个地方开始滑.....复杂度不会超过O(len)
Run ID | Submit Time | Judge Status | Pro.ID | Exe.Time | Exe.Memory | Code Len. | Language | Author |
17477233 | 2016-07-09 18:25:45 | Accepted | 4821 | 670MS | 3348K | 1675 B | C++ | liuyuhong |
#include <cstdio>
#include <cmath>
#include <cstring>
#include <string>
#include <algorithm>
#include <queue>
#include <map>
#include <set>
#include <vector>
#include <iostream>
using namespace std;
typedef unsigned long long ull;
const double pi=acos(-1.0);
double eps=0.000001;
int M,L;
char s[100005];
int base=27;
ull tab[100005];
map<ull ,int > mp;
int main()
{
while(cin>>M>>L)
{
int i,j;
ull powsL_1=1;
for (int i=1; i<=L-1; i++)
powsL_1*=base;
scanf("%s",s);
int len=strlen(s);
int st=0;
ull tmp=0;
for (j=0; j<L; j++)
{
tmp=tmp*base+s[j]-'a'+1;
}
tab[++st]=tmp;
for (i=L; i<len; i++) //滑动预处理所有长度为L的子串的hash值
{
tmp=tmp-(s[i-L]-'a'+1)*powsL_1;
tmp=tmp*base+s[i]-'a'+1;
tab[++st]=tmp;
}
int ans=0;
int k;
for (k=1; k<=L; k++) //从k位置开始滑动
{
mp.clear();
int num=0;
int first=k;
for (i=k; i<=st; i+=L) //每次滑动到下一个l的距离
{
if (mp[tab[i]]==1)
{
mp[tab[first]]--;
first+=L;
i-=L;
num--;
continue;
}
mp[tab[i]]=1;
num++;
if (num==M) //找到符合条件的子串
{
ans++;
mp[tab[first]]--;
first+=L;
num--;
}
}
}
printf("%d\n",ans);
}
return 0;
}