B - Crazy Search 【hash】

给定一个字符串,其中含有不同的字母数量为m,现在求这个字符串中有多少个长度为n且长的互不相同的字符子串 

举个例子, n=3, m=4 ,字符串 "daababac". 长度为3的不同的子串分别是: "daa"; "aab"; "aba"; "bab"; "bac". 因此, 答案是5. 

Input

第一行是两个整数n,m,,一个空格隔开。 接下来一行是我们要解决的字符串.( 你可以认为字符串的长度不会超过一千六百万。)Orz我读错题了,并不是字符串长度不超过1600万,是合理hash之后的hash的值不超过1600万。Orz原谅我

Output

程序应该输出一个整数,对应于给定文本中所找到的大小为n的不同子字符串的数量。

输入数据

3 4
daababac

输出数据

5

TLEcode:map查询是log级别不是O(1)

#include<iostream>
#include<set>
#include<cstring>
#include<cstdio>
using namespace std;
typedef unsigned long long ull;
const int maxn=16e6;
ull has[maxn],a[maxn];
char s[maxn];
const int p=223;
void hash(){
	has[0]=s[0];
	for(int i=1;i<strlen(s);i++){
		has[i]=p*has[i-1]+s[i];
	}
	a[1]=p;
	for(int i=2;i<maxn;i++){
		a[i]=a[i-1]*p;
	}
}
int main(){
	int n,m;
	ull temp;
	set<ull>se;
	scanf("%d%d%s",&n,&m,s);
	hash();
	for(int i=0;i<strlen(s)-n+1;++i){
		if(i) temp=has[i+n-1]-has[i-1]*a[n];
		else temp=has[n-1];
		se.insert(temp);
	}
	cout<<se.size()<<endl;
	return 0;
}
/*
lowerbond
uperbond
*/


/*
k m
has[m]-has[k-1]*a[m-(k-1)]

*/
#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);//substr(i,n) i之后n长度 
            mp[tmp]=i;
        }
        int ans=mp.size();
        printf("%d\n",ans);
    }
    return 0;
} 

ACcode:

#include<cstdio>
#include<cstring>
#include<iostream>
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)!=EOF){
        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;
            }
        }
        cout<<ans<<endl;
    }
    return 0;
}

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值