HUST ACM/ICPC Online Judge Problem 1010–解題報告

來源:互聯網
上載者:User

原題連結:

http://acm.hust.edu.cn/thx/problem.php?id=1010

 

這道題理解起來不難,一般來說第一種解決方案就是暴力求解,但對於ACM題來說,暴力求解往往會得到TLE,也就是逾時。

該題實際上在考察KMP演算法。KMP演算法的介紹詳見:http://baike.baidu.com/view/659777.htm

KMP演算法是字串匹配的經典演算法,它通過給每個字串定義一個特有的特徵向量來逐個匹配字元,使得演算法的複雜度由一般的O(m*n)變成了O(m+n),大大縮短了匹配時間。此題關鍵在於尋找特徵向量的規律性,從而快速得到答案。

 

該題源碼如下:

#define HUST_1010#ifdef HUST_1010#include <iostream>#include<string.h>   #include<stdio.h> using namespace std;#define N 1000002char B[N];int nextx[N];void getnext(int next[],char s[],int l){int i=1,j=0;next[1]=0;while(i<l){if(j==0 || s[i]==s[j]){i++;j++;next[i]=j;}else{j=next[j];}}}int main(){//freopen("TEST\\1010-input.txt","r",stdin);//freopen("TEST\\1010-output.txt","w",stdout);int len;int sum;while(scanf("%s",B+1)!=EOF){sum = 0;len = strlen(B+1);if(len == 1) printf("1\n");else{getnext(nextx,B,len);sum = len - nextx[len]; if( (B[len] == B[len%sum]) || (len%sum == 0 && (B[len] == B[sum]) )  )printf("%d\n",sum);elseprintf("%d\n",len);}}return 0;}#endif

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.