Codeforces Round #299 (Div. 2)D. Tavas and Malekas

时间:2022-02-16 06:00:53

KMP,先预处理按每个节点标记,扫一遍更新每个匹配位置,最后kmp判断是否有重合而且不相同的地方

注意处理细节,很容易runtime error

Codeforces Round #299 (Div. 2)D. Tavas and MalekasCodeforces Round #299 (Div. 2)D. Tavas and Malekas
#include<map>
#include<set>
#include<cmath>
#include<queue>
#include<stack>
#include<vector>
#include<cstdio>
#include<cassert>
#include<iomanip>
#include<cstdlib>
#include<cstring>
#include<iostream>
#include<algorithm>
#define C 0.5772156649
#define pi acos(-1.0)
#define ll long long
#define mod 1000000007
#define ls l,m,rt<<1
#define rs m+1,r,rt<<1|1
#pragma comment(linker, "/STACK:1024000000,1024000000")

using namespace std;

const double g=10.0,eps=1e-7;
const int N=1000000+10,maxn=1000000+10,inf=0x3f3f3f;

int Next[N],a[N];
vector<int>ans;
void getnext(string s)
{
    int k=-1;
    Next[0]=-1;
    for(int i=1;i<s.size();i++)
    {
        while(k>-1&&s[k+1]!=s[i])k=Next[k];
        if(s[k+1]==s[i])k++;
        Next[i]=k;
    }
}
void kmp(string s,string p)
{
    int k=-1;
    for(int i=0;i<s.size();i++)
    {
        while(k>-1&&p[k+1]!=s[i])k=Next[k];
        if(p[k+1]==s[i])k++;
        if(k==p.size()-1)
        {
            ans.push_back(i-p.size()+2);
        }
    }
}
int main()
{
    ios::sync_with_stdio(false);
    cin.tie(0);
    ll n,m;
    string p,s="";
    cin>>n>>m>>p;
    for(int i=0;i<n;i++)s+="?";
    for(int i=0;i<m;i++)
    {
        cin>>a[i];
        s[a[i]-1]=p[0];
    }
    int i=0;
    while(i<n&&s[i]!=p[0])i++;
    int last=i;
    for(;i<n;i++)
    {
        if(s[i]==p[0])last=i;
        if(s[i]=='?'&&i-last>=0&&i<last+p.size())s[i]=p[i-last];
    }
    getnext(p);
    kmp(s,p);
    if(ans.size()<m)
    {
        cout<<0<<endl;
        return 0;
    }
    ll ans=1;
    for(int i=0;i<n;i++)
    {
        if(s[i]=='?')ans=ans*26%mod;
    }
    cout<<ans<<endl;
    return 0;
}
/********************

********************/
View Code