hdu 4763 Theme Section (擴充kmp)

來源:互聯網
上載者:User

hdu 4763 Theme Section (擴充kmp)


很抱歉,之前寫了個很挫o(nlogn)的解法,誤導了大家,後來我仔細想了想,其實用擴充kmp可以o(n)的實現。下面給出具體的實現方法:

解題思路:還是先擴充kmp,把next數組處理出來,

#include<stdio.h>#include<string.h>#include<algorithm>#define lson l , m , rt << 1#define rson m + 1 , r , rt << 1 | 1using namespace std ;const int maxn = 1111111 ;int max ( int a , int b ) { return a > b ? a : b ; }int p[maxn] ;void get_p (const char *T){     int len=strlen(T),a=0;     int i , k ;     p[0]=len;     while(a<len-1 && T[a]==T[a+1]) a++;     p[1]=a;     a=1;     for( k=2;k<len;k++){         int fuck=a+p[a]-1,L=p[k-a];         if( (k-1)+L >= fuck){             int j = (fuck-k+1)>0 ? (fuck-k+1) : 0;             while(k+j<len && T[k+j]==T[j]) j++;             p[k]=j;             a=k;         }         else p[k]=L;     }}char s[maxn] ;int main () {    int t , i ;    scanf ( "%d" , &t ) ;    while ( t -- ) {        scanf ( "%s" , s ) ;        get_p ( s ) ;        int n = strlen ( s ) ;        int mx = 0 ;        int ans = 0 ;        for ( i = n / 3 ; i <= n - 2 * ( n / 3 ) ; i ++ ) mx = max ( mx , p[i] ) ;        int l = n / 3 , r = n - 2 * ( n / 3 ) ;    //    printf ( "l = %d , r = %d\n" , l , r ) ;        for ( i = n / 3 ; i >= 1 ; i -- ) {      //      printf ( "p[%d] = %d , mx = %d\n" , n - i , p[n-i] , mx ) ;            if ( p[n-i] == i && mx >= i ) {                ans = i ;                break ;            }     //       printf ( "l = %d , r = %d " , l , r ) ;            mx = max ( mx , max ( p[--l] , p[++r] ) ) ;            mx = max ( mx , p[++r] ) ; //           printf ( "mx = %d\n" , mx ) ;        }        printf ( "%d\n" , ans ) ;    }    return 0 ;}


相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.