USACO算法系列三十七——shuttle

     题目:http://www.nocow.cn/index.php/Translate:USACO/shuttle

     将左边的所有W移动到最右边,将右边的所有的B移动到最左边。如果通过模拟的话,我觉得会超时,但是并不用模仿每一步移动步骤。

     因为可以通过以下几个规则一定可以得到结果。

     如果"WB_"模式,则"_BW",如果"_WB",则"BW_", 否则轮流移动左右侧的格子。如

     WW_WBBB     //左移动

     WWBW_BB     //跳动B

     WWBWB_B     //右移动

     WWB_BWB    //跳动W

     W_BWBWB    //跳动W

     _WBWBWB    //左移动

     ……

     代码如下:

#include<iostream> #include <fstream> #define SIZE 26 #define W 1 #define B 2 #define LEFT 0 #define RIGHT 1 using namespace std; int n; //棋子个数 int ml =0; int map[SIZE] = {0}; //棋盘 int direct = 0; ifstream fin("shuttle.in"); ofstream fout("shuttle.out"); //移动 int move(int space) { //向左移动 if (space >= 3) { if (map[space-1] == B && map[space-2] == W) { map[space-2] = 0; map[space] = W; return space-2; }//end if }//end if space >=3 //向右移动 if (space <= ml-2) { if (map[space+1] == W && map[space+2] == B) { map[space+2] = 0; map[space] = B; return space+2; } } //左移动 if (direct == LEFT) { if (space>=2) { map[space] = W; map[space-1] = 0; direct = RIGHT; return space-1; }//end space>=2 else { direct = RIGHT; return move(space); } } //右移动 if (direct == RIGHT) { if (space<= ml -1) { map[space] = B; map[space+1] = 0; direct = LEFT; return space + 1; }//end space>=2 else { direct = LEFT; return move(space); } } return -1; } bool isOver(int space) { if (space != n+1) { return false; } for (int i=1; i <=n; i ++) { if (map[i] != B) { return false; }//end if }//end for i for (int i= n+2; i <=ml; i ++) { if (map[i] != W) { return false; } } return true; } int main() { //输入数据 fin >> n; //初始化棋盘 for (int i=1; i <=n; i ++) { map[i] = W; map[n+i+1] = B; } ml = 2 * n + 1; int space = n+1; int temp = 1; space = move(space); fout << space; while (!isOver(space)) { if (temp == 20) { fout << endl; temp = 1; } else { fout << " "; temp ++; } space = move(space); fout << space; } fout << endl; return 0; }

     运行结果如下:

Executing... Test 1: TEST OK [0.000 secs, 3012 KB] Test 2: TEST OK [0.000 secs, 3012 KB] Test 3: TEST OK [0.000 secs, 3012 KB] Test 4: TEST OK [0.011 secs, 3012 KB] Test 5: TEST OK [0.000 secs, 3012 KB] Test 6: TEST OK [0.011 secs, 3012 KB] Test 7: TEST OK [0.000 secs, 3012 KB] Test 8: TEST OK [0.011 secs, 3012 KB] Test 9: TEST OK [0.000 secs, 3012 KB] Test 10: TEST OK [0.011 secs, 3012 KB] All tests OK.

你可能感兴趣的:(USACO算法系列三十七——shuttle)