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

来源:互联网 发布:大数据风险预警 编辑:程序博客网 时间:2024/05/20 13:37
#include <stdio.h>#define DEBUG 1#define TESTCASES 9#define CLOCKS 9#define MOVES 9#define STATES 300000 //4^9 < 3000000int 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 DEBUGint 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);#endifint 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}#endifreturn 0;}

0 0
原创粉丝点击