努力ing
你浪费的今天是昨天死去的人所渴望的明天!!!

广搜的题目

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

用优先队列会超时

时间少,空间大
#include<iostream>
#include<queue>
using namespace std;
int a,b,c,t;
int map[55][55][55];
int dir1[2]={1,-1};
int dir2[4][2]={{1,0},{0,1},{-1,0},{0,-1}};
struct node{
 int x,y,z;
 int time;
};
bool cmp(int v,int w,int u)
{
 if(v<0||v>=a||w<0||w>=b||u<0||u>=c) return 1;
 if(map[v][w][u]==1) return 1;
 return 0;
}
int bfs()
{
 int i,j,k;
 queue<node>q;
 node cur,next;
 cur.x=0;
 cur.y=0;
 cur.z=0;
 cur.time=0;
 q.push(cur);
 while(!q.empty())
 {
  cur=q.front();
  q.pop();
  if(cur.time>t) return -1;
  if(cur.x==a-1&&cur.y==b-1&&cur.z==c-1) return cur.time;
  for(i=0;i<2;i++)
  {
   next.x=cur.x+dir1[i];
   next.y=cur.y;
   next.z=cur.z;
   if(cmp(next.x,next.y,next.z)) continue;
   else{
    next.time=cur.time+1;
    map[next.x][next.y][next.z]=1;
    q.push(next);
   }
  }
  for(i=0;i<4;i++)
  {
   next.x=cur.x;
   next.y=cur.y+dir2[i][0];
   next.z=cur.z+dir2[i][1];
   if(cmp(next.x,next.y,next.z)) continue;
   else{
    next.time=cur.time+1;
    map[next.x][next.y][next.z]=1;
    q.push(next);
   }
  }
 
 }
 return -1;
}
int main()
{
 int l,i,j,k;
 scanf("%d",&l);
 while(l--)
 {
  scanf("%d%d%d%d",&a,&b,&c,&t);
  for(i=0;i<a;i++)
  {
   for(j=0;j<b;j++)
   {
    for(k=0;k<c;k++)
    {
     scanf("%d",&map[i][j][k]);
    }
   }
  }

 cout<<bfs()<<endl;
 }
 return 0;
}

 

第二种做法     时间多,空间小

#include<iostream>
#include<queue>
using namespace std;
int a,b,c,t;
int map[55][55][55];
int dir[6][3]={{0,1,0},{0,0,1},{0,-1,0},{0,0,-1},{1,0,0},{-1,0,0}};
struct node{
 int x,y,z;
 int time;
};
bool cmp(int v,int w,int u)
{
 if(v<0||v>=a||w<0||w>=b||u<0||u>=c) return 1;
 if(map[v][w][u]==1) return 1;
 return 0;
}
int bfs()
{
 int i,j,k;
 queue<node>q;
 node cur,next;
 cur.x=0;
 cur.y=0;
 cur.z=0;
 cur.time=0;
 q.push(cur);
 while(!q.empty())
 {
  cur=q.front();
  q.pop();
  if(cur.time>t) return -1;
  if(cur.x==a-1&&cur.y==b-1&&cur.z==c-1) return cur.time;
  for(i=0;i<6;i++)
  {
   next.x=cur.x+dir[i][0];
   next.y=cur.y+dir[i][1];
   next.z=cur.z+dir[i][2];
   if(cmp(next.x,next.y,next.z)) continue;
   else{
    next.time=cur.time+1;
    map[next.x][next.y][next.z]=1;
    q.push(next);
   }
  }
 
 }
 return -1;
}
int main()
{
 int l,i,j,k;
 scanf("%d",&l);
 while(l--)
 {
  scanf("%d%d%d%d",&a,&b,&c,&t);
  for(i=0;i<a;i++)
  {
   for(j=0;j<b;j++)
   {
    for(k=0;k<c;k++)
    {
     scanf("%d",&map[i][j][k]);
    }
   }
  }

 cout<<bfs()<<endl;
 }
 return 0;
}

  

posted on 2013-05-19 22:02  努力ing  阅读(128)  评论(0)    收藏  举报