The nature of HDU3746 loop section

Conclusion: circular section is equal to the array length minus the length of the next value of the array
that is: num = len-next [len ] num len section of an array of a minimum cycle length

associated derivation stamp here

#include <bits/stdc++.h>

using namespace std;
const int MAXN = 1e5+7;
// 由此题得到一个重要的结论 循环节的长度 = len-next[len];len代表数组的长度
int Next[MAXN];
char s[MAXN];
void getNext(char str[])
{
    
    
	int j = 0,k = -1;
	Next[0] = -1;
	int len = strlen(str);
	while(j < len){
    
    
		if(k == -1 || str[k] == str[j]){
    
    //当前没有同 或者next可边长的时候
			Next[++j] = ++k;
		}
		else{
    
    
			k = Next[k];//回溯的过程
		}
	}
}
int main()
{
    
    
	int t;
	scanf("%d",&t);
	getchar();
	while(t--){
    
    
		scanf("%s",s);
		int len = strlen(s);
		getNext(s);
		//for(int i = 0;i <= len;i ++) printf("%d ",Next[i]);
		int num = len-Next[len];
		//printf("%d\n",num);
		if(len%num == 0&&num != len) printf("0\n");
		else printf("%d\n",num-len%num);
	}
	return 0;
}

Guess you like

Origin blog.csdn.net/weixin_45672411/article/details/107255524