题目链接:http://poj.org/problem?id=1200
题目大意:给定整数n和nc,以及一个很长很长的字符串,问长度为n的子串有多少个?nc表示总共有几个字母,最终的答案不超过16000000.
解题思路:本题由于字符串长度未知,但知道很长很长,后缀数组什么的靠边站,复杂度又高程序又难写。所以用了个hash,先为出现的每个字母赋个值(0至nc-1),然后计算每个长度为n的子串的hashva,未出现过ans++即可。
测试数据:
3 4
daababac
abc
adcbeadeba
代码:
#include <stdio.h>
#include <string.h>
#include <math.h>
#define MAX 17000000
bool hash[MAX];
char str[MAX];
int n,nc,ans,strtot;
int hashval,key[1000],arr[1000];
int main()
{
int i,j,k,len;
while (scanf("%d%d",&n,&nc) != EOF) {
scanf("%s",str);
ans = strtot = 0;
len = strlen(str);
memset(arr,0,sizeof(arr));
memset(key,0,sizeof(key));
memset(hash,false,sizeof(hash));
for (i = 0; i < len; ++i)
if (!key[str[i]]) key[str[i]] = strtot++;
for (i = 0; i <= len - n; ++i) {
hashval = 0;
for (j = i; j < i + n; ++j)
hashval += key[str[j]] * (int)pow(nc*1.0,j-i);
if (hash[hashval] == false) ans++,hash[hashval] = true;
}
if (len < n) printf("0\n");
else printf("%d\n",ans);
}
}
本文章ZeroClock原创,但可以转载,因为我们是兄弟。