(POJ

来源:互联网 发布:ubuntu怎么dakaiexe 编辑:程序博客网 时间:2024/06/05 14:56

(POJ - 1200)Crazy Search

Time Limit: 1000MS Memory Limit: 65536K
Total Submissions: 29747 Accepted: 8267

Description

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.

题目大意:给出一个字符串,里面只有nc个不同的字母,问这个字符串可以分成多少种n长度的字符串。

思路:因为不同字母只有nc个,所以可以用nc进制表示n长度的字符串(当然要先把字符转化成对于的数字),最后只要判断nc进制数不同的有多少个就行,这个用hash表就可以完成。

#include<cstdio>#include<cstring>using namespace std;const int maxn=16000005;char a[maxn];bool hash[maxn];int num[150];int main(){    int n,nc;    while(~scanf("%d%d",&n,&nc))    {        memset(num,0,sizeof(num));        memset(hash,0,sizeof(hash));        scanf("%s",a);        int len=strlen(a);        int cnt=0;        for(int i=0;i<len;i++)            if(!num[a[i]]) num[a[i]]=cnt++;        int ans=0;        for(int i=0;i<=len-n;i++)        {            int sum=0;            for(int j=i;j<=i+n-1;j++)                sum=sum*nc+num[a[j]];            if(!hash[sum])            {                ans++;                hash[sum]=1;            }        }        printf("%d\n",ans);    }    return 0;}

杭电有一题和这题完全类似的题目,只不过杭电的数据比较水,规定时间也有5s,所以杭电那题还可以用map将字符串和数字一一映射做,先给出链接:HDU1381和用map做的代码。

#include<cstdio>#include<iostream>#include<string>#include<map>using namespace std;int main(){    int T;    scanf("%d",&T);    while(T--)    {        int n,nc;        scanf("%d%d",&n,&nc);        map<string,int> mp;        string s,tmp;        cin>>s;        for(int i=0;i<=s.size()-n;i++)        {            tmp.assign(s,i,n);            mp[tmp]=i;        }        int ans=mp.size();        printf("%d\n",ans);    }    return 0;} 
原创粉丝点击