【字符串】Segment Occurrences

Codeforces Round 48 (Rated for Div. 2)


大意:输入字符串s和t、各自的长度和q个询问,询问由第l到r个字母构成的s的子串中,包含t的个数


一开始的傻屌代码,TLE上天了

#include <iostream>
#include <string>
#include <cstdio>
using namespace std;
int n,m,w,sum=0;
string s,t;
int main()
{
	int n,m,q;
	scanf("%d%d%d",&n,&m,&q);//s长度,n长度,q次数
	s.resize(1200);
	t.resize(1200);
	scanf("%s%s",&s[0],&t[0]);//s串,t串
	int l,r,ans=0;
	while(q--)
	{
		ans=0;
		scanf("%d%d",&l,&r);
		if(r-l+1>=m) 
		{
			for(int i=l-1;i+m-1<r;i++)
			{
				string temp=s.substr(i,m);
				if(s.substr(i,m)==t.substr(0,m)) ans++;
			}
		}
		printf("%d\n",ans);

	}
}

后来采用了类似打表的思想过了。

#include<iostream>
#include<cstdio>
#include<string>
using namespace std; 
int a[1200];
int main()
{
    int n,m,k,q,l,r,ans;
    string s,t;
    cin>>n>>m>>q;
    cin>>s>>t;
    for(int i=0; i<=n-m; i++)
        if(s.substr(i,m)==t)
            a[i]=1;
    while(q--)
    {
        ans=0;
        cin>>r>>l;
        for(int i=r-1; i<=l-m; i++)
            if(a[i])
                ans++;
        cout<<ans<<endl;
    }
    return 0;
}
 

别人家的题解:

用find的:

#include<cstdio>
#include<cstring>
#include<string>
#include<iostream>
#include<algorithm>
using namespace std;
int main()
{
    int n,m,q,i,j,l,r,len;
    int counts;
    int vis[10010];
    string s1,s2;
    cin>>n>>m>>q;
    cin>>s1>>s2;
    len=s2.size();
    memset(vis,0,sizeof(vis));
    string::size_type pos=0;
    while((pos=s1.find(s2,pos))!=string::npos)
    {
        vis[pos+1]=pos+1;
        pos++;
    }
    for(i=1;i<=q;i++)
    {
        counts=0;
        scanf("%d%d",&l,&r);
        for(j=l;j<=r;j++)
        {
            if(vis[j]!=0&&vis[j]+len-1<=r)
            {
               counts++;
            }
        }
        printf("%d\n",counts);
    }
    return 0;
}

还有前缀数组的大佬:

#include <bits/stdc++.h>
using namespace std;
int n,m,q;
string s,t;
int l,r;
int hay[10000],shay[10000];
int main()
{
    cin>>n>>m>>q;
    cin>>s>>t;
    s=" "+s;
    t=" "+t;
    for(int i=1;i<=n-m+1;i++)
    {
        hay[i]=1;
        for(int j=0;j<m;j++)
        {
            if(s[i+j]!=t[1+j])
            {
                hay[i]=0;
                break;
            }
        }
        shay[i]=shay[i-1]+hay[i];
    }

    while(q--)
    {
        cin>>l>>r;
        r=r-m+1;
        if(r<l) cout<<"0"<<endl;
        else cout<<shay[r]-shay[l-1]<<endl;
    }
    return 0;
}

 

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值