题解 P4391 【[BOI2009]Radio Transmission 无线传输】

· · 题解

刚学完KMP不到1小时就来做这道题,本题对next数组的理解和运用很巧妙

所以最终我们的答案即为 n-next[n]

代码:

#include<stdio.h>
#include<iostream>
#include<cstring>
using namespace std;
int n,len,next[1000005];
char s[1000005];

int main()
{
    scanf("%d %s",&n,s+1);
    int t1=0,t2;
    next[0]=t2=-1;
    while(t1<=n)
    {
        if(t2==-1||s[t2+1]==s[t1+1])
            next[++t1]=++t2;
        else
            t2=next[t2];
    }
    printf("%d",n-next[n]);
    return 0;
}