hdu3746 kmp求循环节

题意:给一个已知序列,求使其拥有至少两个循环最少需要增加多少个字符(只能在头和尾增加)

首先循环节,就想到kmp的next数组,next当next[i]>i/2则在i之前存在两个或以上循环,用len-next【len】可以得到最小所需要的循环节长度。

这题不知道怎么回事,用gegchar就tle,估计是哪里写死循环了。

代码:

#include<cstdio>
#include<cstdlib>
#include<iostream>
#include<cstring>
using namespace std;
int t;
char b[1000005];
int NEXT[1000005];
void getNEXT(int t)
{
	int j=0,k=-1;
	int m=t;
	NEXT[0]=-1;
	NEXT[m]=0;
	while(j<m){
		if(k==-1||b[j]==b[k])
		{
			NEXT[++j]=++k;
		}
		else
		{
			k=NEXT[k];
		}
	}
}

int main()
{
	scanf("%d",&t);
	//char c;
	//c=getchar();
	for(int i=1;i<=t;i++)
	{

        //memset(NEXT,0,sizeof(NEXT));
        int tt=0;
		//while(c<'a'||c>'z')c=getchar();
		//while(c>='a'&&c<='z'){
			//b[tt++]=c;
			//c=getchar();
		//}
		scanf("%s",b);
		tt=strlen(b);
		int end=tt-1;
		getNEXT(tt);
		int cnt=0;

        cnt=tt-NEXT[end+1];
		if(NEXT[end+1]>0&&NEXT[end+1]%cnt==0)printf("0\n");
		else
			printf("%d\n",cnt-NEXT[end+1]%cnt);

//		printf("%d\n",(NEXT[b.length()-1]>0&&NEXT[b.length()-1]%cnt==0?0:cnt-NEXT[b.length()-1]%cnt));
	}
}

  

#include<cstdio>#include<cstdlib>#include<iostream>#include<cstring>using namespace std;int t;char b[1000005];int NEXT[1000005];void getNEXT(int t){int j=0,k=-1;int m=t;NEXT[0]=-1;NEXT[m]=0;while(j<m){if(k==-1||b[j]==b[k]){NEXT[++j]=++k;}else{k=NEXT[k];}}}
int main(){scanf("%d",&t);//char c;//c=getchar();for(int i=1;i<=t;i++){
        //memset(NEXT,0,sizeof(NEXT));        int tt=0;//while(c<'a'||c>'z')c=getchar();//while(c>='a'&&c<='z'){//b[tt++]=c;//c=getchar();//}scanf("%s",b);tt=strlen(b);int end=tt-1;getNEXT(tt);int cnt=0;
        cnt=tt-NEXT[end+1];if(NEXT[end+1]>0&&NEXT[end+1]%cnt==0)printf("0\n");elseprintf("%d\n",cnt-NEXT[end+1]%cnt);
//printf("%d\n",(NEXT[b.length()-1]>0&&NEXT[b.length()-1]%cnt==0?0:cnt-NEXT[b.length()-1]%cnt));}}

猜你喜欢

转载自www.cnblogs.com/witRY/p/9712705.html