天天看點

USACO 1.3 Prime Cryptarithm (剪枝)

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

#define MAX_DIGITS 9
int numOfDigits;
int used[MAX_DIGITS + 1];

int isDigitsUsed(int factor, int digits){;
	while ( factor != 0){
		digits--;
		if (used[factor % 10] == 0)
			return 0;
		factor /= 10;
	}
	if (digits == 0)
		return 1;
	else
		return 0;
}

int isMatch(int firstFactor, int secondFactor){
	if (isDigitsUsed(firstFactor, 3) == 0 ||
		isDigitsUsed(secondFactor, 2) == 0 ||
		isDigitsUsed(firstFactor * secondFactor, 4) == 0 )
		return 0;
	while (secondFactor != 0){
		if (isDigitsUsed( (secondFactor % 10) * firstFactor, 3) == 0)
			return 0;
		secondFactor /= 10;
	}
	return 1;
}

int main(){
#if DEBUG
	int testCase;
	for (testCase = 1; testCase <= TESTCASES; testCase++){
		char inputFileName[20] = "inputX.txt";
		inputFileName[5] = '1' +  (testCase - 1);
		freopen(inputFileName, "r", stdin);
		printf("\n#%d\n", testCase);
#endif

	int digit;
	for (digit = 1; digit <= MAX_DIGITS; digit++)
		used[digit] = 0;

	scanf("%d", &numOfDigits);
	int indexOfDigit;
	for (indexOfDigit = 1; indexOfDigit <= numOfDigits; indexOfDigit++){
		scanf("%d", &digit);
		used[digit] = 1;
	}

	int numOfSolutions = 0;
	int firstFactor, secondFactor;
	for (firstFactor = 100; firstFactor < 10000; firstFactor++)
		for (secondFactor = 10; secondFactor < 100; secondFactor++)
			if (isMatch(firstFactor, secondFactor) == 1)
				numOfSolutions++;
	
	printf("%d\n", numOfSolutions);

#if DEBUG
	}
#endif
	return 0;	
}
           

繼續閱讀