zoukankan      html  css  js  c++  java
  • hdu3336 Count the string 扩展KMP

    It is well known that AekdyCoin is good at string problems as well as number theory problems. When given a string s, we can write down all the non-empty prefixes of this string. For example:
    s: "abab"
    The prefixes are: "a", "ab", "aba", "abab"
    For each prefix, we can count the times it matches in s. So we can see that prefix "a" matches twice, "ab" matches twice too, "aba" matches once, and "abab" matches once. Now you are asked to calculate the sum of the match times for all the prefixes. For "abab", it is 2 + 2 + 1 + 1 = 6.
    The answer may be very large, so output the answer mod 10007.

    题意:求一个字符串和它所有前缀的匹配次数总和,如'abab'与前缀'ab'匹配次数为2。

    用扩展KMP与自身匹配。

     1 #include<stdio.h>
     2 #include<string.h>
     3 #include<algorithm>
     4 using namespace std;
     5 
     6 const int maxn=2e5+5;
     7 const int mod=1e4+7;
     8 
     9 char s[maxn];
    10 int ext[maxn],nxt[maxn];
    11 
    12 void EKMP(char s[],char t[],int lens,int lent){
    13     int i,j,p,l,k;
    14     nxt[0]=lent;j=0;
    15     while(j+1<lent&&t[j]==t[j+1])j++;
    16     nxt[1]=j;
    17     k=1;
    18     for(i=2;i<lent;i++){
    19         p=nxt[k]+k-1;
    20         l=nxt[i-k];
    21         if(i+l<p+1)nxt[i]=l;
    22         else{
    23             j=max(0,p-i+1);
    24             while(i+j<lent&&t[i+j]==t[j])j++;
    25             nxt[i]=j;
    26             k=i;
    27         }
    28     }
    29 
    30     j=0;
    31     while(j<lens&&j<lent&&s[j]==t[j])j++;
    32     ext[0]=j;k=0;
    33     for(i=1;i<lens;i++){
    34         p=ext[k]+k-1;
    35         l=nxt[i-k];
    36         if(l+i<p+1)ext[i]=l;
    37         else{
    38             j=max(0,p-i+1);
    39             while(i+j<lens&&j<lent&&s[i+j]==t[j])j++;
    40             ext[i]=j;
    41             k=i;
    42         }
    43     }
    44 }
    45 
    46 int main(){
    47     int T;
    48     scanf("%d",&T);
    49     while(T--){
    50         int n;
    51         scanf("%d%s",&n,s);
    52         EKMP(s,s,n,n);
    53         int cnt=0;
    54         for(int i=0;i<n;++i){
    55             cnt=(cnt+ext[i])%mod;
    56         }
    57         printf("%d
    ",cnt);
    58     }
    59     return 0;
    60 }
    View Code
  • 相关阅读:
    中文繁体简体互换试验
    msSQL2005数据库备份
    C#实现Base64编码与解码
    C#中正则表达式的高级应用
    滚动条样式锦集
    远程MSMQ
    Silverlight+WCF 新手实例 象棋 主界面事件区求和认输(三十二)
    MSSQL 2005 数据库变成可疑状态
    CYQ.Data 轻量数据层之路 华丽升级 V1.3出世(五)
    CYQ.Data 轻量数据层之路 终极升级(二)
  • 原文地址:https://www.cnblogs.com/cenariusxz/p/6592548.html
Copyright © 2011-2022 走看看