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

#include 
#define DEBUG 1
#define TESTCASES 9
#define CLOCKS 9
#define MOVES 9
#define STATES 300000 //4^9 < 3000000
int queue[STATES];
int head, tail;
//既可以记录前个状态,又可以而作状态被访问过的标记
int pre[STATES];
int sequence[STATES];
int stack[28];
int top;
int arrayOfMoves[MOVES][MOVES] = { {1, 1, 0, 1, 1, 0, 0, 0, 0},
				   {1, 1, 1, 0, 0, 0, 0, 0, 0},
				   {0, 1, 1, 0, 1, 1, 0, 0, 0},
				   {1, 0, 0, 1, 0, 0, 1, 0, 0},
				   {0, 1, 0, 1, 1, 1, 0, 1, 0},
                                   {0, 0, 1, 0, 0, 1, 0, 0, 1},
                                   {0, 0, 0, 1, 1, 0, 1, 1, 0},
                                   {0, 0, 0, 0, 0, 0, 1, 1, 1},
                                   {0, 0, 0, 0, 1, 1, 0, 1, 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 initialState = 0;
	int clock;
	for (clock = 0; clock < CLOCKS; clock++){
		int colckState;
		scanf("%d", &colckState);
		initialState = (initialState << 2) + ( (colckState / 3) & 3 );
	}
	
	int state;
	for (state = 0; state < STATES; state++)
		pre[state] = -1;

	head = tail = 0;
	queue[tail++] = initialState;
	pre[initialState] = 0;

	while (head < tail){
		int statePoped = queue[head++];
		int clockState[CLOCKS];
		for (clock = 0; clock < CLOCKS; clock++)
			clockState[clock] = ( statePoped >> ( 2 * (CLOCKS - clock - 1) ) ) & 3;
		int move;
		for (move = 0; move < MOVES; move++){
			int state = 0;
			for (clock = 0; clock < CLOCKS; clock++)
				state = (state << 2) + ( ( clockState[clock] + arrayOfMoves[move][clock] ) & 3 );
			if (pre[state] == -1){
				pre[state] = statePoped;
				sequence[state] = move;
				if (state == 0){
					top = 0;
					stack[top++] = sequence[state];
					state = pre[state];
					while (state != initialState){
						stack[top++] = sequence[state];
						state = pre[state];
					}
					while (--top >= 0)
						printf("%d%c", stack[top] + 1, top == 0 ? '\n' : ' ');
					goto DONE;
				}
				queue[tail++] = state;			
			}
		}
	}
	DONE: ;
#if DEBUG
	}
#endif
	return 0;
}

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