HDU 4300 Clairewd’s message (next函數的應用)

題意:給你一個明文對密文的字母表,在給你一段截獲信息,截獲信息前半段是密文,後半段是明文,但不清楚它們的分界點在哪裏,密文必定是完整的,明文多是殘缺的,求完整的信息串(即完整的密文+明文串)。函數

題解:KMP next函數的應用。spa

 

#include <cstdio>
#include <cstring>
#include <cstdlib>

const int MAXN = 100010;

char table[32];
char extable[32];
char ori[MAXN];
char aft[MAXN];
int next[MAXN];
int  len;

void init()
{
    for ( int i = 0; i < 26; ++i )
        extable[ table[i]-'a' ] = 'a' + i;

    len = strlen(ori);
    for ( int i = 0; i < len/2; ++i )
        aft[i] = ori[i];

    for ( int i = len/2; i < len; ++i )
        aft[i] = table[ ori[i] - 'a' ];

    aft[len] = '\0';

    return;
}

void getNext( char* s, int* next )
{
    int length = len;
    int i = 0, j = -1;
    next[0] = -1;
    while ( i < length )
    {
        if ( j == -1 || s[i] == s[j] )
        {
            ++i, ++j;
            next[i] = j;
        }
        else j = next[j];
    }
}

int main()
{
    int T;
    scanf( "%d", &T );
    while ( T-- )
    {
        scanf( "%s", table );
        scanf( "%s", ori );
        init();
        getNext( aft, next );

        int ans = len;
        //printf("next[%d] = %d\n", ans, next[ans] );
        while ( next[ans] > len/2 ) ans = next[ans];
        ans = len - next[ans];
        //printf( "ans = %d\n", ans );
        for ( int i = 0; i < ans; ++i )
            printf( "%c", ori[i] );
        for ( int i = 0; i < ans; ++i )
            printf( "%c", extable[ ori[i] - 'a' ] );
        puts("");
    }
    return 0;
}
相關文章
相關標籤/搜索