URAL 1684 Jack's Last Word

#include<stdio.h>
#define MAX_LONG 75001

char S[MAX_LONG];
char T[MAX_LONG];
int next[MAX_LONG];
int subStrLen[MAX_LONG];
int numOfSubStrs;

int getLen(char *string){
	char *p = string;
	while (*p != '\0'){
		p++;
	}
	return p - string;
}

int main(){
	freopen("input.txt", "r", stdin);
	//用S去匹配T
	scanf("%s %s", S, T);

	int SLen = getLen(S);

	//关键一步啊,要把S最后的字符串也求取next并运用KMS
	S[SLen] = '#';
	SLen++;

	int TLen = getLen(T);

	int prefix = -1;
	int suffix = 0;
	next[suffix] = -1;
	while (suffix < SLen - 1){
		if (-1 == prefix || S[prefix] == S[suffix]){
			prefix++;
			suffix++;
			if (S[prefix] != S[suffix]){
				next[suffix] = prefix;
			} else {
				next[suffix] = next[prefix];
			}
		} else {
			prefix = next[prefix];
		}
	}

	int SIndex = 0;
	int TIndex = 0;
	numOfSubStrs = 0;
	while (SIndex < SLen && TIndex < TLen){
		if (-1 == SIndex){
			printf("Yes\n");
			return 0;
		} 
		if (S[SIndex] == T[TIndex]){
			SIndex++;
			TIndex++;
		} else {
			SIndex = next[SIndex];
			subStrLen[numOfSubStrs++] = TIndex - SIndex;
		}
	}

	printf("No\n");
	int start = 0;
	int i, j;
	for (i = 0; i < numOfSubStrs; i++){
		for (j = start; j < subStrLen[i]; j++){
			printf("%c", T[j]);
		}
		printf(" ");
		start = subStrLen[i];
	}

	for (j = start; j < TLen; j++){
		printf("%c", T[j]);
	}
	printf("\n");
	
	return 0;
}

你可能感兴趣的:(word,last,KMS,ural,1684,Jacks)