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

#include <stdio.h>
#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;
}

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值