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;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值