输入空格hdu - 1010 - Tempter of the Bone
时间紧张,先记一笔,后续优化与完善。
题意:一个N*M的地图,走过的点不能再走,X为墙弗成走,能否从点S到点D恰好用时T。(1 < N, M < 7; 0 < T < 50)
标题链接:http://acm.hdu.edu.cn/showproblem.php?pid=1010
——>>有点数典忘祖的感觉,寒假时用cin输入数据,轻松AC,后来渐渐改成了用scanf来输入,明天,这道坑爹的标题交了n次也是WA,取代了n种方式后发明,是输入的问题,料想是输入的地图有空格……
超时优化的思想:
1、可走格子数少于T时,必定不ok;
2、从格子A到格子B,无论怎么走,步数的奇偶性相同。
用时很少的写法:
#include <cstdio> #include <cmath> #include <iostream> using namespace std; char MAP[8][8]; int N, M, T, s_x, s_y, d_x, d_y; int dx[] = {-1, 0, 1, 0}; int dy[] = { 0, 1, 0, -1}; bool ok; void dfs(int x, int y, int cur) { if(ok) return; int temp = T - cur - abs(d_x-x) - abs(d_y-y); if((temp < 0) || (temp % 2 == 1)) return; for(int i = 0; i < 4; i++) { int new_x = x + dx[i]; int new_y = y + dy[i]; if(new_x >= 0 && new_x < N && new_y >= 0 && new_y < M && MAP[new_x][new_y] != 'X') { if(new_x == d_x && new_y == d_y && cur+1 == T) ok = 1; else { MAP[new_x][new_y] = 'X'; dfs(new_x, new_y, cur+1); MAP[new_x][new_y] = '.'; } } } } int main() { int i, j, sum; while(scanf("%d%d%d", &N, &M, &T) == 3) { if(N == 0 && M == 0 && T == 0) return 0; sum = 1; for(i = 0; i < N; i++) { //getchar(); for(j = 0; j < M; j++) { //MAP[i][j] = getchar(); //scanf("%c", &MAP[i][j]); cin>>MAP[i][j]; if(MAP[i][j] == 'S') { s_x = i; s_y = j; } else if(MAP[i][j] == 'D') { d_x = i; d_y = j; } else if(MAP[i][j] == 'X') sum++; } } sum = N*M - sum; ok = 0; MAP[s_x][s_y] = 'X'; if(T <= sum) dfs(s_x, s_y, 0); if(ok) printf("YES\n"); else printf("NO\n"); } return 0; }
vis[][]数组写法:
#include <cstdio> #include <iostream> #include <cstring> #include <cmath> using namespace std; const int maxn = 7 + 10; int dx[] = {-1, 1, 0, 0}; int dy[] = { 0, 0, -1, 1}; char MAP[maxn][maxn]; bool ok, vis[maxn][maxn]; int N, M, T, Dx, Dy; void dfs(int x, int y, int cur) { if(ok) return; if(cur == T) { if(x == Dx && y == Dy) { ok = 1; return; } else return; } int temp = T - cur - (Dx - x) - (Dy - y); if(temp < 0 || (temp&1)) return; for(int i = 0; i < 4; i++) { int newx = x + dx[i]; int newy = y + dy[i]; if(newx >= 0 && newx < N && newy >= 0 && newy < M && MAP[newx][newy] != 'X' && !vis[newx][newy]) { vis[newx][newy] = 1; dfs(newx, newy, cur+1); vis[newx][newy] = 0; } } } int main() { int Sx, Sy, i, j; while(scanf("%d%d%d", &N, &M, &T) == 3) { if(!N && !M && !T) return 0; for(i = 0; i < N; i++) { for(j = 0; j < M; j++) { cin>>MAP[i][j]; if(MAP[i][j] == 'S') { Sx = i; Sy = j; } else if(MAP[i][j] == 'D') { Dx = i; Dy = j; } } } ok = 0; memset(vis, 0, sizeof(vis)); vis[Sx][Sy] = 1; dfs(Sx, Sy, 0); if(ok) printf("YES\n"); else printf("NO\n"); } return 0; }
文章结束给大家分享下程序员的一些笑话语录: 很多所谓的牛人也不过如此,离开了你,微软还是微软,Google还是Google,苹果还是苹果,暴雪还是暴雪,而这些牛人离开了公司,自己什么都不是。
--------------------------------- 原创文章 By 输入和空格 ---------------------------------