USACO 2.3 Longest Prefix

#include <stdio.h>
#define DEBUG 0
#define TESTCASES 6

typedef struct Primitive{
	char str[11];
	int len;
}Primitive;
Primitive PrimitiveArray[201];
int list;
char sequence[200001];
int canGet[200001];

void stringCopy(char *to, char *from){
	while (*from != '\0'){
		*to = *from;
		to++;
		from++;
	}
	*to = '\0';
}

int stringLength(char *str){
	char *move = str;
	while (*move != '\0')
		move++;
	return move - str;
}

void stringCatenate(char *destination, char *source){
	while (*destination != '\0')
		destination++;
	stringCopy(destination, source);
}


int main(){
#if DEBUG
	int testCase;
	for (testCase = 1; testCase <= TESTCASES; testCase++){
		char inputFileName[20] = "input6.txt";
		inputFileName[5] = '1' +  (testCase - 1);
		freopen(inputFileName, "r", stdin);
		printf("\n#%d\n", testCase);
#endif
	
	list = 0;
	char str[11];
	while (scanf("%s", str) != EOF){
		if(str[0] == '.')
			break;
		stringCopy(PrimitiveArray[list].str, str);
		PrimitiveArray[list].len = stringLength(str);
		list++;
	}
	sequence[0] = '\0';
	while (scanf("%s", str) != EOF)
		stringCatenate(sequence, str);
	int sequenceLen = stringLength(sequence);

	int i;
	for (i = 0; i < sequenceLen; i++)
		canGet[i] = 0;
	canGet[0] = 1;

	int result = 0;
	for (i = 0; i <= sequenceLen; i++){
		if (!canGet[i])
			continue;
		int PrimitiveIndex;
		for (PrimitiveIndex = 0; PrimitiveIndex < list; PrimitiveIndex++){
			int PrimitiveLen = PrimitiveArray[PrimitiveIndex].len;
			int tempLen = i + PrimitiveLen;
			if (tempLen > sequenceLen)
				break;
			int match = 1;
			int j;
			for (j = 0; j < PrimitiveLen; j++){
				if ( PrimitiveArray[PrimitiveIndex].str[j] != sequence[i + j]){
					match = 0;
					break;
				}
			}
			if (match){
				canGet[tempLen] = 1;
				if (tempLen> result)
					result = tempLen;
			}
		}
	}

	printf("%d\n", result);

#if DEBUG
	}
#endif
	return 0;
}

你可能感兴趣的:(USACO,prefix,longest,2.3)