题解:P8199 [传智杯 #4 决赛] 游戏

· · 题解

实际上这道题很难简单 废话少说,上代码

#include<bits/stdc++.h>
using namespace std;
int main()
{
    vector<int> next;
    string s;
    string cz = "chuanzhi";
    cin >> s;
    int n, m;
    int count = 0;
    n = s.size();
    m = cz.size();
    int x=1;
    int now=0;
    next.push_back(0);
    while (x < m)
    {
        if (cz[now] == cz[x])
        {
            now++;
            x++;
            next.push_back(now);
        }
        else if(now) now=next[now-1];
        else next.push_back(0), x++;
    }
    int i=0,j=0;
    while (i<n)
    {
        if (s[i]==cz[j])
        {
            i++;
            j++;
        }
        else if(j) j=next[j-1];
        else
        {
            i++;
        }
        if(j==7)
        {
            count++;
            j=next[j-1];
        }
    }
    cout<<count;
}