poj 2406 Power Strings(KMP || 暴力)

题目链接:http://poj.org/problem?id=2406

没想到这道题暴力都能过,而且只有188ms。。。

①kmp(125ms):

#include<iostream>
#include<cstdio>
#include<cstring>
#include<math.h>
#include<algorithm>
using namespace std;

const int INF=0x3f3f3f3f;
const int maxn=1000010;
int T,n,m;
int next[maxn];
char s[maxn];

void getNext(char *s){
	int i=0,j=-1;
	next[0]=-1;
	while(s[i]!='\0'){
		if(j==-1||s[i]==s[j]){
			i++,j++;
			next[i]=j;
		}
		else
			j=next[j];
	}
}

int main() {
#ifndef ONLINE_JUDGE
	freopen("test.in","r",stdin);
	freopen("test.out","w",stdout);
#endif
	while(~scanf("%s",s)){
		if(!strcmp(s,".")) break;
		getNext(s);
		int len=strlen(s);
		if(len%(len-next[len])==0)
			printf("%d\n",len/(len-next[len]));
		else
			printf("1\n");
	}
	return 0;
}


②暴力(188ms):

#include<iostream>
#include<cstdio>
#include<cstring>
#include<math.h>
#include<algorithm>
using namespace std;

const int INF=0x3f3f3f3f;
const int maxn=1000010;
int T,n,m;
char s[maxn],subs[maxn];

bool ok(char *a,char *b){
	int len=strlen(a);
	for(int i=0;i<len;i++)
		if(a[i]!=b[i])
			return false;
	return true;
}

int main() {
#ifndef ONLINE_JUDGE
	freopen("test.in","r",stdin);
	freopen("test.out","w",stdout);
#endif
	while(~scanf("%s",s)){
		if(!strcmp(s,".")) break;
		int len=strlen(s);
		for(int i=1;i<=len;i++){
			if(len%i!=0) continue;
			bool flag=true;
			strcpy(subs,s+len-i);
			for(int j=0;j<=len-i;j+=i){
				if(!ok(subs,s+j)){
					flag=false;
					break;
				}
			}
			if(flag){
				printf("%d\n",len/i);
				break;
			}
		}
	}
	return 0;
}


你可能感兴趣的:(poj 2406 Power Strings(KMP || 暴力))