首页 > 代码库 > HDU 1253 胜利大逃亡

HDU 1253 胜利大逃亡

题目链接:http://acm.hdu.edu.cn/showproblem.php?pid=1253


解析

这道题目非常容易TLE,所以我们需要三维BFS+剪枝。


代码

#include <iostream>
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <cmath>
#include <algorithm>
#include <vector>
#include <queue>
#include <stack>
#include <set>
#include <map>
using namespace std;
#define Lowbit(x) ((x)&(-(x)))
#define ll long long
#define mp make_pair
#define ff first
#define ss second
#define pb push_back
#define mod 10000007
//#define LOCAL
#define MAXN 100010
#define INF 1e9
#define Max 100010

typedef struct node{
    int x,y,z;
    int cost;
}NODE;

bool flag[55][55][55];  //标记是否访问过
int p[55][55][55];      //记录地图
//六个方向
int tx[]={0,0,0,0,1,-1};
int ty[]={0,1,0,-1,0,0};
int tz[]={1,0,-1,0,0,0};
int A,B,C,T;

bool check(int x,int y,int z){
    if(x<0||x>=A||y<0||y>=B||z<0||z>=C||flag[x][y][z]||p[x][y][z])
        return false;
    return true;
}

int main(){
    int K;
    scanf("%d", &K);
    while(K--){
        queue<NODE> que;
        scanf("%d%d%d%d", &A,&B,&C,&T);
        memset(flag, false, sizeof(flag));
        int i,j,k;
        for(i=0; i<A; ++i){
            for(j=0; j<B; ++j){
                for(k=0; k<C; ++k){
                    scanf("%d", &p[i][j][k]);
                    step[i][j][k] = -1;
                }
            }
        }

        //BFS
        NODE now={0,0,0,0};
        int ans = -1;
        que.push(now);
        flag[0][0][0] = true;
        while(!que.empty()){
            now = que.front();
            que.pop();
            if(now.cost>T)  break;
            if(now.x==A-1&&now.y==B-1&&now.z==C-1){
                ans = now.cost;
                break;
            }
            NODE tmp;
            for(i=0; i<6&&flag; ++i){
                tmp.x = now.x+tx[i];
                tmp.y = now.y+ty[i];
                tmp.z = now.z+tz[i];
                tmp.cost = now.cost+1;
                if(check(tmp.x,tmp.y,tmp.z)){
                    flag[tmp.x][tmp.y][tmp.z] = true;
                    //剪枝,当该点以最快速度都不能在规定时间到达时,去掉
                    if(tmp.cost+abs(tmp.x-A+1)+abs(tmp.y-B+1)+abs(tmp.z-C+1)>T)
                        continue;
                    que.push(tmp);
                }
            }
        }
        printf("%d\n", ans);
    }
    return 0;
}

HDU 1253 胜利大逃亡