HDU 3746 Cyclic Nacklace (KMP 循環節)

題目鏈接

題意:給定字符串,問最少添加多少個字符串能讓其循環。

分析:從KMP的next數組定義可以知道:

next[i] : 滿足 x[i-k…i-1]=x[0…k-1] 的最大 k 值
(最長公共前後綴的長度)

從這題看就是 已經相等的前後綴的長度, 那麼 same=len - next [len] 最小循環節的長度。

  • 如果 nx[len] = 0 ,前面都沒有相同前後綴,所以輸出 len
  • 如果 len%same = 0 ,說明整段都是循環的,所以輸出 0
  • 其他情況下,輸出 same - len%same 就是缺的字符個數

PS:奇妙wa的原因是 關閉輸出流,不能直接cout<<0

#include <iostream>
#include <cmath>
#include <iomanip>
#include <cstring>
#include <vector>
#include <string>
#include <map>
#include <queue>
#include <stack>
#include <set>
#include <cstdio>
#include <algorithm>
#define INF 0x3f3f3f3f
#define PI acos(-1)
using namespace std;
typedef long long ll;
typedef pair<string, string> P;
const int mod=1e9+7;
const int maxn=1e5+10;


int nx[maxn];

void getnx(string x){
	int m=x.size();
	int i,j;
	j=nx[0]=-1;
	i=0;
	while (i<m){
		if (j==-1 || x[i]==x[j]){
			i++,j++;
			nx[i]=j;
		}
		else j=nx[j];
	}
}
string s;
int main() {
	ios::sync_with_stdio(0);
	cin.tie(0);
	cout.tie(0);
	int T;
	cin>>T;
	while (T--){
		memset(nx,0,sizeof(nx));
		cin>>s;	
		getnx(s);
		int len=s.size();
		int same=len-nx[len];
		if (nx[len]==0) cout<<len<<endl;
		else if (len%same==0) cout<<"0"<<endl; 
		else cout<<same-len%same<<endl;		
	}
	return 0;
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章