---
title: "[KMP-NEXT数组特性]HDU 3336 Count the string"
author: "Coco_young"
date: "2012-06-27T11:39:00Z"
tags: []
slug: "kmp-next-hdu-3336-count-the-string"
draft: false
lastmod: "2013-02-03T02:37:19Z"
id: 1786442
url: "https://coco-young.iteye.com/blog/1786442"
---

传送门：[http://acm.hdu.edu.cn/showproblem.php?pid=3336](http://acm.hdu.edu.cn/showproblem.php?pid=3336)

题目大意：给定一个字符串（1-200000），求出其所有前缀在自身中匹配成功的次数之和（模10007）

解题思路：利用next数组的特性，next\[pos]在主串指针在pos位置失配时，子串指针应该调整到next\[pos]与pos进行比较，这意味着0-(next\[pos]-1)的字符串应该和(pos-next\[pos])-(pos-1)字符串相同，而0-(next\[pos]-1)的字符串正好是该字符串的前缀，解法就很自然了，在获得字符串0-N的next值，枚举i属于\[1,N]，记录pos = i, 如果pos &gt; 0 , 累加答案，pos = next\[pos]，否则累加i的值。

代码：

```
#include<iostream>
using namespace std;
const int MAXN = 222222,MOD = 10007;
char s[MAXN];
int T,N,next[MAXN];
void makenext(){
    int i = 0,j = -1;
    next[0] = -1;
    while(i<=N){
        if(s[i]==s[j]||j==-1)next[++i] = ++j;
        else j = next[j];
    }
}
int solve(){
    int sum = 0,pos;
    for(int i=1;i<=N;i++){
        pos = i;
        while(pos){
            sum = (sum+1)%MOD;
            pos = next[pos];
        }
    }
    return sum;
}
int main(){
    scanf("%d",&T);
    while(T--){
        scanf("%d",&N);
        scanf("%s",s);
        makenext();
        printf("%d\n",solve());
    }
    return 0;
}
```