Poj~1200 Crazy Search (Hash哈希算法)

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

Hint

Huge input,scanf is recommended.

题意是:给一串含有n个不同字符的字符串,问这个字符串有多少种m个字符的子串,最后输出个数。

#include<iostream>
#include<cstdio>
#include<cstring>
#include<algorithm>
using namespace std;
const int N=16000005;
int m,n;
char str[N];
int hash[N];
int vis[500];
int main()
{
    while(~scanf("%d%d%s",&m,&n,str))
    {
        int num=0;
        int len=strlen(str);
        vis[0]=num++; //第一个字符编号为0
        for(int i=1;i<len;++i)//遍历所有的字符串
        {
            if(vis[str[i]]==0)//如果没出现过
                vis[str[i]]=num++;;//就给它编号
        }
        int ans=0;
        for(int i=0;i<=len-m;++i)//遍历长度为m的子串
        {
            int sum=0;
            for(int j=0;j<m;++j)
            {
                sum=sum*num+vis[str[i+j]];//字符串转化为数字
            }
            if(!hash[sum])//第一次出现该字符串
            {
                hash[sum]=1;
                ans++;
            }
        }
        printf("%d\n",ans);
    }
    return 0;
}

 

    原文作者:哈希算法
    原文地址: https://blog.csdn.net/gao506440410/article/details/81779259
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞