HDU 4333 扩展KMP

题目链接

题意:

给一个特大数字长度<=100000,现在依次将最后一位数字放置在第一位,求这些数字中比初始数字小的有多少个,相等的有多少个,大的有多少个(数字不可以重复)。

思路:

对原字符串进行倍增后作为母串S,原字符串作为子串T,进行扩展KMP处理。对于Ex[i]==len的位置说明以此处为初始的字符串与原串相等,当Ex[i]<len时我们只需比较S[i+Ex[i]]与T[Ex[i]]即可。注意数字不可以重复,所以我们需要计算一下循环节!

C++代码:

#include<bits/stdc++.h>
using namespace std;
const int maxn = 100010;
const int maxm = 200010;

int Next[maxn],Ex[maxm];

void GetKmpNext( char *s , int *Next )
{
    Next[0] = -1;
    int len = strlen(s);
    for ( int i=0,j=-1 ; i<len ; i++ )
    {
        while( j!=-1&&s[i]!=s[j] )
            j = Next[j];
        Next[i+1] = ++j;
    }
}

void GetNext( char *s , int *Next )
{
    int c = 0,len = strlen(s);
    Next[0] = len;
    while( s[c]==s[c+1]&&c+1<len ) c++;
    Next[1] = c;
    int po = 1;
    for ( int i=2 ; i<len ; i++ )
    {
        if ( Next[i-po]+i<Next[po]+po )
            Next[i] = Next[i-po];
        else
        {
            int t = Next[po]+po-i;
            if ( t<0 ) t = 0;
            while( i+t<len&&s[t]==s[i+t] ) t++;
            Next[i] = t;
            po = i;
        }
    }
}

void ExKmp( char *s1 , char *s2 , int *Next , int *Ex )
{
    int c = 0,len = strlen(s1),l2 = strlen(s2);
    GetNext( s2 , Next );
    while( s1[c]==s2[c]&&c<len&&c<l2 ) c++;
    Ex[0] = c;
    int po = 0;
    for ( int i=1 ; i<len ; i++ )
    {
        if ( Next[i-po]+i<Ex[po]+po )
            Ex[i] = Next[i-po];
        else
        {
            int t = Ex[po]+po-i;
            if ( t<0 ) t = 0;
            while ( i+t<len&&t<l2&&s1[i+t]==s2[t] ) t++;
            Ex[i] = t;
            po = i;
        }
    }
}

char SS[maxm],S[maxn];

int main()
{
    int Cas; scanf ( "%d" , &Cas );
    for ( int cas=1 ; cas<=Cas ; cas++ )
    {
        scanf ( "%s" , S );
        GetKmpNext( S , Next );
        int len = strlen(S);
        int d = (len%(len-Next[len])==0)?len/(len-Next[len]):1;
        strcpy( SS , S );
        for ( int i=len ; i<len+len ; i++ )
            SS[i] = S[i-len];
        SS[len+len] = '\0';
        ExKmp( SS , S , Next , Ex );
        int a = 0,b = 0,c = 0;
        for ( int i=0 ; i<len ; i++ )
        {
            if ( Ex[i]==len ) b++;
            else if ( SS[i+Ex[i]]<S[Ex[i]] ) a++;
            else if ( SS[i+Ex[i]]>S[Ex[i]] ) c++;
        }
        printf ( "Case %d: %d %d %d\n" , cas , a/d , b/d , c/d );
    }
    return 0;
}

猜你喜欢

转载自blog.csdn.net/game_acm/article/details/81000149
今日推荐