USACO算法系列四十五——wissqu

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

     采用的是深度搜索的方法。发现现在使用深度搜索的频率不断升高了。其实程序昨天就写好了,但是怎么运行都没有结果,调试也觉得没有问题,一度让我处于崩溃的边缘。休息了一天,今天重新调试了一下,发现原来是数据输入的时候出错了。A:3,B:3,C:3,D:4,E:3。写成了A:3,B:3,C:4,D:3,E:3。难怪一直没有结果了。

    代码如下:

#include <iostream> #include <fstream> #include <string.h> struct Move { int x; int y; int cow; }; //牛棚 int shed[6][6]; int ycow[6] = {0,3,3,3,4,3}; int isuse[17][6] = {0}; bool take[17] ={false}; Move result[17]; bool isfirst = true; int number = 0; using namespace std; ifstream fin("wissqu.in"); ofstream fout("wissqu.out"); void print() { for (int i=1; i<17; i ++) { char c = result[i].cow + 'A' -1; fout << c << " " << result[i].x << " "<< result[i].y <<endl; } } void init() { memset(isuse, 0, sizeof(int) * 17 * 6); for (int i=1; i <=4; i ++) { for (int j=1; j<=4; j ++) { int index = (i-1) * 4 + j; isuse[index][shed[i-1][j-1]] = 1; isuse[index][shed[i-1][j]] = 1; isuse[index][shed[i-1][j+1]] = 1; isuse[index][shed[i][j-1]] = 1; isuse[index][shed[i][j]] = 1; isuse[index][shed[i][j+1]] = 1; isuse[index][shed[i+1][j-1]] = 1; isuse[index][shed[i+1][j]] = 1; isuse[index][shed[i+1][j+1]] = 1; }//end for j }//end for i } void DFSWissqu(int step) { if (step == 17) { if (isfirst) { print(); number ++; isfirst = false; }//end isfirst else number ++; return; } for (int i=1; i < 6; i ++) { if (ycow[i]>0) { for (int j=1; j < 17; j ++) { if (isuse[j][i] == 0&&take[j] == false) { int x, y =0; if (j%4 ==0) { y=4; x = j/4; } else { x = (int)(j/4 + 1); y = j % 4; } result[step].cow = i; result[step].x = x; result[step].y = y; ycow[i] --; int oldc = shed[x][y]; take[j] = true; shed[x][y] = i; init(); DFSWissqu(step+1); shed[x][y] = oldc; init(); take[j] = false; ycow[i] ++; }//end if isuse[j][i] == 0 } }//end if } } int main() { for (int i=0; i< 6; i++) { shed[0][i] = shed[5][i] = shed[i][0] = shed[5][i] = 0; } //输入数据 for (int i=1; i <= 4; i ++) { for (int j=1; j <= 4; j ++) { char c; fin >> c; shed[i][j] = c- 'A' + 1; }//end for }//end for i init(); for (int j=1; j < 17; j ++) { if (isuse[j][4] == 0&&take[j] == false) { int x, y =0; if (j%4 ==0) { y=4; x = j/4; } else { x = (int)(j/4 + 1); y = j % 4; } result[1].cow =4; result[1].x = x; result[1].y = y; ycow[4] --; int oldc = shed[x][y]; take[j] = true; shed[x][y] = 4; init(); DFSWissqu(2); shed[x][y] = oldc; init(); take[j] = false; ycow[4]++; }//end if isuse[j][i] == 0 } fout << number <<endl; return 0; }

    运行结果如下:

Executing... Test 1: TEST OK [3.499 secs, 3028 KB] All tests OK.

你可能感兴趣的:(USACO算法系列四十五——wissqu)