USACO 1.4 The Clocks (位操作+枚举+DFS)

#include 
#define DEBUG 1
#define TESTCASES 9
#define INF (1 << 31 - 1)
#define CLOCKS 9
#define MOVES 9

int arrayOfMoves[MOVES + 1] = {0, 18911232, 19136512, 2363904, 16810048, 2134536, 262657, 36936, 73, 4617};
int set = 57521883;
int minTurns;
int finalSequence;

void turnDials(int state, int move, int numOfTurns, int sequence){
	if (numOfTurns > minTurns)
		return;

	if (move > MOVES){
		if (state == 0){
			if (numOfTurns < minTurns){
				minTurns = numOfTurns;
				finalSequence = sequence;
			} else if (sequence > finalSequence)
				finalSequence = sequence;
		}
		return;
	}

	int timesOfMove;
	for (timesOfMove = 0; timesOfMove <= 3; timesOfMove++){
		int newState = (state + arrayOfMoves[move] * timesOfMove) & set;
		//移位操作符优先级很低,注意加上各种括号
		int newSequence = sequence + (timesOfMove << (2 * (MOVES - move)));
		turnDials(newState, move + 1, numOfTurns + timesOfMove, newSequence);
	}
}

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 initialState = 0;
	int clock;
	for (clock = 1; clock <= CLOCKS; clock++){
		int colckState;
		scanf("%d", &colckState);
		initialState = (initialState << 3) + (colckState / 3 % 4);
	}

	minTurns = 28;
	finalSequence = 0;
	turnDials(initialState, 1, 0, 0);

	int move;
	for (move = 1; move <= MOVES; move++){
		int timesOfMove = ( finalSequence >> (2 * (MOVES - move) ) ) & 3;
		while (timesOfMove-- > 0){
			printf("%d%c", move, minTurns == 1 ? '\n' : ' ');
			minTurns--;
		}
	}

#if DEBUG
	}
#endif
	return 0;
}

你可能感兴趣的:(Talk,is,cheap,Show,me,the,code,ACM-ICPC,USACO,The,Clocks,位操作,DFS,枚举)