hdu 4763

求一个最长的字串s,原串中有sasbs的形式。
枚举是会TLE滴,所以要预处理一下原来的串,can[i]表示能否构成长度为i的字串的一前一后的形式,这用next数组即可求得,然后枚举中间的点判断能否满足三段式的结构

#include <cstdio>
#include <cstring>
#include <algorithm> 

const int N = 1e6 + 10;
char s[N];
int net[N],n,can[N];
void KMP(){
	int len = strlen(s);
	int i = 0,j;
	j = net[0] = -1;
	while(i < len){
		while(j != -1 && s[i] != s[j]) j = net[j];
		net[++i] = ++j;
	} 
}
int main(){
	scanf("%d",&n);
	while(n--){
		scanf("%s",s);
		KMP();
		int ans = 0,len = strlen(s);
		memset(can,0,sizeof(can));
		int t = len;
		while(t > 0){
			if(t * 2 <= len) can[t] = 1;
			t = net[t];
		}
		for(int i = len;i>=2;i--){
			if(net[i] < ans) continue;
			t = i; 
			while(t > 0 ){
				if(can[t] && i >= 2 * t && i + t <= len){
					ans = std::max(ans,t);
					break;
				}
				t = net[t];
			}
		}
		printf("%d\n",ans);
	}
	return 0;
} 

猜你喜欢

转载自blog.csdn.net/winhcc/article/details/89819154