hdu 3613 Best Reward 扩展kmp

 

#include<iostream>
#include<cstring>
#include<cstdio>
using namespace std;
const int MM=500100;
int next1[MM],extand1[MM];
int next2[MM],extand2[MM];
int sum[MM];
char S[MM],T[MM];
int val[30];
void GetNext(const char *T,int *next){
     int len=strlen(T),a=0;
     next[0]=len;
     while(a<len-1 && T[a]==T[a+1]) a++;
     next[1]=a;
     a=1;
     for(int k=2;k<len;k++){
         int p=a+next[a]-1,L=next[k-a];
         if( (k-1)+L >= p){
             int j = (p-k+1)>0 ? (p-k+1) : 0;
             while(k+j<len && T[k+j]==T[j]) j++;
             next[k]=j;
             a=k;
         }
         else
             next[k]=L;
     }
}
void GetExtand(const char *S,const char *T,int *next,int *extand){
     GetNext(T,next);
     int slen=strlen(S),tlen=strlen(T),a=0;
     int MinLen = slen < tlen ? slen : tlen;
     while(a<MinLen && S[a]==T[a]) a++;
     extand[0]=a;
     a=0;
     for(int k=1;k<slen;k++){
         int p=a+extand[a]-1, L=next[k-a];
         if( (k-1)+L >= p){
             int j= (p-k+1) > 0 ? (p-k+1) : 0;
             while(k+j<slen && j<tlen && S[k+j]==T[j]) j++;
             extand[k]=j;
             a=k;
         }
         else
             extand[k]=L;
     }
}

int main()
{
    int cas;
    scanf("%d",&cas);
    while(cas--)
    {
        int now=-1;
        int i,j;
        for(int i=0; i<26; ++i)
            scanf("%d",&val[i]);
        scanf("%s",S);
        int len=strlen(S);
        memset(sum, 0, sizeof(sum));
        sum[0]=val[S[0]-'a'];
        for(i=1; i<len; ++i)
            sum[i] = val[S[i]-'a']+sum[i-1];
        strcpy(T,S);
        strrev(T);
        GetExtand(S,T,next1,extand1);
        GetExtand(T,S,next2,extand2);
        int Max=0;
        for(i=1;i<len;i++)
        {
            now=0;
            if(i+extand2[i]==len)
                now+=sum[len-i-1];
            if(len-i+extand1[len-i]==len)
                now=now+sum[len-1]-sum[len-i-1];
            if(now>Max) Max=now;
        }
        printf("%d\n",Max);
    }
    return 0;
}


 

posted @ 2014-06-15 15:15  贝尔摩德  阅读(127)  评论(0编辑  收藏  举报