USACO 1.5 Checker Challenge (位操作)

#include <stdio.h>
#define DEBUG 1
#define TESTCASES 8
#define IN(x)  ( (x) >= 1 && (x) <= size ? 1 : 0 )
#define WITHIN(x, y) ( IN(x) && IN(y) ? 1 : 0 )
int size;
int allQueensPlacedState;

int solution[14];
int numOfSolutions;

void printColumnsCanPlaceIn(int columnsCanPlaceIn){
	int i;
	for (i = size - 1; i >= 0; i--)
		printf("%d ", (columnsCanPlaceIn >> i) & 1 ? 1 : 0);
	printf("\n");
}

void placeQueen(int row, int columnState, int leftDiagonalState, int rightDiagonalState){
	if (columnState == allQueensPlacedState){
		numOfSolutions++;
		if (numOfSolutions < 4){
			int i;
			for (i = 1; i <= size; i++)
				printf("%d ", solution[i]);
			printf("\n");
		}
	}
	int columnsCanPlaceIn = allQueensPlacedState & ~(columnState | leftDiagonalState | rightDiagonalState);
	//printColumnsCanPlaceIn(columnsCanPlaceIn);
	while (columnsCanPlaceIn != 0){
		//取columnsCanPlaceIn最后边的1赋给columnToPlaceIn
		int columnToPlaceIn;
		int i;
		for (i = 0; i < size; i++){
			if( ((1 << i) & columnsCanPlaceIn) != 0){
				columnToPlaceIn = 1 << i;
				if (numOfSolutions < 4)
					solution[row] = i + 1;
				break;
			}
		}
		columnsCanPlaceIn = columnsCanPlaceIn - columnToPlaceIn;
		placeQueen(row + 1,
				 columnState + columnToPlaceIn,
				 (leftDiagonalState + columnToPlaceIn) << 1,
				 (rightDiagonalState + columnToPlaceIn) >> 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

	scanf("%d", &size);

	allQueensPlacedState =  (1 << size) - 1;
	numOfSolutions = 0;
	placeQueen(1, 0, 0, 0);
	printf("%d\n", numOfSolutions);

#if DEBUG
	}
#endif
	return 0;
}


 
 
 

你可能感兴趣的:(USACO,位操作,1.5,checker,N皇后,challenge)