HDU 3336

来源:互联网 发布:虚拟机nat网络配置 编辑:程序博客网 时间:2024/05/15 23:49

 思路:KMP,但要对其进行变形,当找到失败位置时,要继续考察该位置,一直向前找到字符串首不能再向前找,因为我们不只要计算该子串本身,我们还要计算该子串包含的其他子串,因为这些子串都是原串的子串,这是显然的。


#include<stdio.h>#include<string.h>int fail[200005];int sum[200005]; char str[200005]; int T, m, max;  void getfail(){    fail[0] = -1;    int i, j, temp;     for(i = 1, j = -1; i < m; i ++)    {        while(j >= 0 && str[j + 1] != str[i])        {            j = fail[j];         }        if(str[j + 1] == str[i])            j ++;         fail[i] = j;        if(j >= 0)        {            sum[j] ++;             if(max < j)                max = j;             temp = j;             while(temp >= 0)            {                temp = fail[temp];                 sum[temp] ++;             }        }    }}    int main(int argc, char const *argv[])     {        int i, cnt;         scanf("%d", &T);         while(T--)        {            memset(str, 0, sizeof(str));             memset(sum, 0, sizeof(sum));             scanf("%d", &m);             cnt = m % 10007;             max = 0;             getchar();             fgets(str, m+1,stdin);              getfail();             for(i = 0; i <= max; i ++)            {                /* printf("OK\n"); */                sum[i] %= 10007;                 cnt += sum[i];                 cnt %= 10007;             }            printf("%d\n", cnt);        }        return 0;     }


0 0
原创粉丝点击