题目:http://www.nocow.cn/index.php/Translate:USACO/snail
直接深度搜索。我还以为会超时,没想到AC了。代码如下:
#include <iostream> #include <fstream> #define SIZE 121 #define UP 0 #define RIGHT 1 #define DOWN 2 #define LEFT 3 using namespace std; struct Corner { int x; int y; }; ifstream fin("snail.in"); ofstream fout("snail.out"); int n; int map[SIZE][SIZE] = {0}; int b; int result = 0; void DFSSnail(Corner c, int load) { bool flag = false; int walk = 0; Corner temp; for (int i=0; i < 4; i ++) { temp = c; if (i == UP) { for (int j=c.x-1; j>=1; j --) { if (map[j][c.y] == 0) { map[j][c.y] = 1; temp.x = j; walk++; }//end if map[j][c.y] == 0 else if (map[j][c.y] == 2) { break; }//end if -1 else if(map[j][c.y] == 1) { flag = true; break; }//end if 1 }//end for j }//end if i == UP else if (i == RIGHT) { for (int j=c.y+1; j<= n;j++) { if (map[c.x][j] == 0) { map[c.x][j] = 1; walk ++; temp.y = j; }//end if 0 else if (map[c.x][j] == 2) { break; }//end if -1 else { flag = true; break; } }//end for } else if (i == DOWN) { for (int j=c.x+1; j <=n; j ++) { if (map[j][c.y] == 0) { temp.x = j; walk ++; map[j][c.y] = 1; }//end if 0 else if (map[j][c.y] == 2) { break; } else { flag = true; break; } } } else if (i == LEFT) { for (int j=c.y-1; j>=1; j --) { if (map[c.x][j] ==0) { map[c.x][j] = 1; walk ++; temp.y = j; }//end if else if (map[c.x][j] == 2) { break; } else { flag = true; break; } }//end fro } if (flag) { result = result > (load+walk) ? result : (load+walk); flag = false; } else { if (walk>0) { DFSSnail(temp, load+walk); }//end walk } if (walk>0) { if (i == UP) { for (int j= temp.x; j < c.x; j++) { map[j][c.y] = 0; } } else if (i == RIGHT) { for (int j=temp.y; j > c.y; j --) { map[c.x][j] = 0; } } else if ( i== DOWN) { for (int j=temp.x; j>c.x; j --) { map[j][c.y] = 0; } } else if (i == LEFT) { for (int j=temp.y; j < c.y; j ++) { map[c.x][j] = 0; } } }//end if walk walk = 0; }//end for i } int main() { //输入数据 fin>> n >> b; for (int i=0; i < b; i ++) { char c = '/0'; fin >> c; int y = c - 'A' + 1; int x; fin >> x; map[x][y] = 2; } Corner cor; cor.x = 1; cor.y = 1; map[1][1] = 1; DFSSnail( cor,1); fout << result << endl; return 0; }
运行结果如下:
Executing... Test 1: TEST OK [0.000 secs, 3068 KB] Test 2: TEST OK [0.011 secs, 3068 KB] Test 3: TEST OK [0.011 secs, 3068 KB] Test 4: TEST OK [0.011 secs, 3068 KB] Test 5: TEST OK [0.022 secs, 3068 KB] Test 6: TEST OK [0.000 secs, 3068 KB] Test 7: TEST OK [0.000 secs, 3068 KB] Test 8: TEST OK [0.022 secs, 3068 KB] Test 9: TEST OK [0.011 secs, 3068 KB] Test 10: TEST OK [0.000 secs, 3068 KB] Test 11: TEST OK [0.000 secs, 3068 KB] Test 12: TEST OK [0.022 secs, 3068 KB] All tests OK.