题目连接ios
Descriptionc++
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.app
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.ide
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.this
Outputspa
The program should output just an integer corresponding to the number of different substrings of size N found in the given text.code
Sample Inputorm
3 4
daababacip
Sample Output
5
分析:
给定一个有nc个不一样的字符组成的字符串,而后询问这个字符串里面有多少个长度为n的不彻底相同的子串。
首先想到的就是对于这个字符串使用字符串截取函数获取每个子串,而后利用map来判重。可是这样的话时间会超时,转换一下利用hash的思想来求解。
明确指出是该字符串由nc个不一样的字符组成,咱们将这nc个字符串对应成nc进制,对应的时候与字符的ASCLL码表没有关系,至于该字符第一次在字符串中出现的顺序有关(固然这个能够根据本身的习惯来定义)
例如题目上给出的:daababac
对应成 4进制后是:01121213
而后根据转换后的进制数,将每个子串对应成一个一一对应的数字,就能够利用hash在O(1)的时间内进行判重,会大大减小时间。
须要注意的一点就是,由于咱们是按照nc进制来求数值的,而不是习惯全部的10进制,说以应该乘上的是nc。
代码:
#include<stdio.h> #include<iostream> #include<algorithm> #include<string.h> using namespace std; int num[300]; int Hash[16000009];//hash函数 int main() { int n,nc; string str; while(~scanf("%d%d",&n,&nc)) { memset(Hash,0,sizeof(Hash)); cin>>str; int len=str.length(); int cnt=1; num[str[0]]=0; for(int i=1; i<len; i++) //将nc个字符转换为对应的nc进制的数,字母和数字是一一对应的 { if(num[str[i]]==0)//只有当这个字符没有转换过的时候,才将该字符对应成一个数字 { num[str[i]]=cnt; cnt++; } } int ans=0,sum; for(int i=0; i<=len-n; i++) { sum=0; for(int j=i; j<i+n; j++) { sum=sum*nc+num[str[j]];//特别要注意这里由于是nc进制的计算因此乘上的是nc,不要由于咱们习惯的十进制计算而乘上10 } //这样每个长度为n的不一样的子串都会惟一的对应一个数字 if(Hash[sum]==0) { Hash[sum]=1; ans++; } } printf("%d\n",ans); } return 0; }