http://acm.hdu.edu.cn/showproblem.php?pid=4198

今天杭电热身赛的B题,读完题就上手写dfs,结果爆栈了,500*500的规模对暴力递归来说有点多。

然后就是bfs,遇到@时先放入另一队列,当当前step>que[head].step时que[head]入队(这里可以证明que[head]的step是que总的最小值)。第一个出口便为最终解。

思路就这样,结果写出来各种bug各种蛋疼。最后直接调晕了...

code:

#include<cstdio>
#include<cstring>
#define Min(a, b)   a>b?b:a
struct node{
    int x, y ;
    int step ;
}q[250001] ;
node que[250001] ;
char data[505][505] ;
int tur[4][2] = {010, -110, -10} ;
int h, w, d, ans ;
bool vis[505][505] ;
void bfs(int x, int y){
    int he, r ;
    int head, rear ;
    he = r = 0 ;
    head = rear = 0 ;
    q[r].x = x ;
    q[r].y = y ;
    q[r++].step = 0 ;
    vis[x][y] = true ;
    while(r>he){
        node p = q[he++] ;
        while(head<rear&&que[head].step<=p.step){
            q[r++] = que[head++] ;
        }
        for(int i=0; i<4; i++){
            node temp = p ;
            temp.x += tur[i][0] ;
            temp.y += tur[i][1] ;
            if(temp.x<0||temp.x>=h||temp.y<0||temp.y>=w){
                p.step ++ ;
                ans = p.step ;
                return ;
            }
            if(vis[temp.x][temp.y]||data[temp.x][temp.y]=='#')  continue ;
            vis[temp.x][temp.y] = true ;
            if(data[temp.x][temp.y]=='@'){
                temp.step = p.step + d + 1 ;
                que[rear++] = temp ;
            }
            else if(data[temp.x][temp.y]=='.'){
                temp.step = p.step + 1 ;
                q[r++] = temp ;
            }
        }
        if(he==r&&head<rear)
            q[r++] = que[head++] ;
    }
    return ;
}
int main(){
    int t, i, j, sx, sy ;
    scanf("%d", &t) ;
    while(t--){
        scanf("%d%d%d", &h, &w, &d) ;
        memset(vis, falsesizeof(vis)) ;
        for(i=0; i<h; i++){
            getchar() ;
            scanf("%s", data[i]) ;
            for(j=0; j<w; j++){
                if(data[i][j]=='S')
                    sx = i, sy = j ;
            }
        }
        bfs(sx, sy) ;
        printf("%d\n", ans) ;
    }
    return 0 ;} 
posted on 2012-04-03 19:57  追逐.  阅读(405)  评论(1)    收藏  举报