zoukankan      html  css  js  c++  java
  • Cyclic Nacklace HDU 3746 KMP 循环节

    Cyclic Nacklace HDU 3746 KMP 循环节

    题意

    给你一个字符串,然后在字符串的末尾添加最少的字符,使这个字符串经过首尾链接后是一个由循环节构成的环。

    解题思路

    next[len]-len的差即是循环部分的长度。 这个是重点。这个题目自己开始没有想明白,看的博客,推荐这个

    代码实现

    #include<cstdio>
    #include<cstring>
    #include<algorithm>
    using namespace std;
    const int maxn=1e5+7;
    char str[maxn];
    int nt[maxn];
    void getnext(char *p, int len)
    {
    	int i=0, k=-1;
    	nt[0]=-1;
    	while(i<len)
    	{
    		if(k==-1 || str[i]==str[k])
    			nt[++i]=++k;
    		else 
    			k=nt[k];
    	}
    }
    int main()
    {
    	int t, len, i, cnt=0;
    	scanf("%d", &t);
    	while(t--)
    	{
    		scanf("%s", str);
    		len=strlen(str);
    		for(int i=0; i<=len; i++)
    			nt[i]=0;
    		getnext(str, len);
    		if(nt[len]==0)
    			printf("%d
    ", len);
    		else if(len%(len-nt[len])==0)
    			printf("0
    ");
    		else 
    		{	
    			int len1=len-nt[len];//最小循环节的长度
    			printf("%d
    ", len1-len%len1); 
    		}
    	}
    	return 0;
    }
    
    欢迎评论交流!
  • 相关阅读:
    18软工实践-第三次作业-结对项目1
    结对作业之代码规范
    ALPHA(7)
    ALPHA(6)
    ALPHA(五)
    404 Note Found 现场编程
    ALPHA(四)
    ALPHA冲刺(三)
    ALpha冲刺(二)
    ALPHA 冲刺(一)
  • 原文地址:https://www.cnblogs.com/alking1001/p/11773672.html
Copyright © 2011-2022 走看看