Many people like to solve hard puzzles some of which may lead them to madness. One such puzzle could be finding a hidden prime number in a given text. Such number could be the number of different substrings of a given size that exist in the text. As you soon will discover, you really need the help of a computer and a good algorithm to solve such a puzzle.
Your task is to write a program that given the size, N, of the substring, the number of different characters that may occur in the text, NC, and the text itself, determines the number of different substrings of size N that appear in the text.
As an example, consider N=3, NC=4 and the text “daababac”. The different substrings of size 3 that can be found in this text are: “daa”; “aab”; “aba”; “bab”; “bac”. Therefore, the answer should be 5.
Input
The first line of input consists of two numbers, N and NC, separated by exactly one space. This is followed by the text where the search takes place. You may assume that the maximum number of substrings formed by the possible set of characters does not exceed 16 Millions.
Output
The program should output just an integer corresponding to the number of different substrings of size N found in the given text.
Sample Input
3 4
daababac
Sample Output
5
输入n:在所给字符串种,每n个字符为一个字串
输入nc:有nc种字符(nc=4,则有abcd四种)
输入字符串
题目说characters does not exceed 16 Millions.……有点大,还要快速搜索,用哈希表试一试。
代码如下
//输入n,nc,字符串
//先对字母赋值
#include<cstdio>
#include<string>
#include<cstring>
using namespace std;
const int maxn=16000050;
char str[maxn];
int hash[maxn]={0};
int vis[300]={0};
int n,nc;
int main()
{
int i,j;
while(scanf("%d %d %s",&n,&nc,str)!=EOF)
{
int len=strlen(str);
int cnt=0;
//对字母赋值,如d=1,a=2,b=3,c=4
int num=0;
for(i=0;i<len;i++)
{
if(!vis[str[i]])
vis[str[i]]=++num;
if(num==nc)
break;
}
//遍历字串(长度为n)
for(i=0;i<=len-n;i++)//从最开始一直到len-n个,j是0
到n-1,所以str[i+j]是0到2,1大到3,……len-n到len-1
{
int ans1=0;
//int x=i;
for(j=0;j<n;j++)
{
ans1=ans1*num+vis[str[i+j]];//计算每个子列的值
//这里用的直接定地址法,如A*key+B的形式,a,b可以随意
}
if(hash[ans1]==0)//如果子列值为0,则表示没有出现过,cnt++进行计数
{
cnt++;
hash[ans1]=1;
}
}
printf("%d\n",cnt);
}
}
然后,为什么用set超时,是因为set储存方式吗,是平衡数,有些操作时间是log?