您的位置:首页 > 其它

HDU1401 双广BFS

2013-02-14 23:02 183 查看
分别从s,e出发进行bfs

注意讨论的部分即可。

详见代码:

View Code

#include<stdio.h>
#include<string.h>
#include<stdlib.h>
#include<queue>
#include<map>
#include<algorithm>
using namespace std;
const int maxn = 8;
const int inf = 123456789;
struct node{
int x,y;
};
struct node2{
int t;
node pos[4];
}s,e;
map<int,int>mp;
map<int,int>::iterator it;
const int dx[]={0,0,1,-1};
const int dy[]={1,-1,0,0};

bool out( int x,int y ){
if( x>=0&&x<8&&y>=0&&y<8 )
return false;//no out
else
return true;
}

bool out2( node2 now ){
for( int i=0;i<4;i++ ){
if( out(now.pos[i].x,now.pos[i].y)==true )
return true;//is out
}
return false;
}

bool cmp( node n1,node n2 ){
if( n1.x!=n2.x )
return n1.x<n2.x;
else
return n1.y<n2.y;
}

bool exist( node2 p,int k ){
for( int i=0;i<4;i++ ){
if( i!=k ){
if( p.pos[ i ].x==p.pos[ k ].x&&p.pos[ i ].y==p.pos[ k ].y )
return true;//has exist
}
}
return false;
}

int get_hash(node *tmp){
int res=0;
sort(tmp,tmp+4,cmp);
for(int i=0;i<4;i++){
res|=(tmp[i].x<<(6*i));
res|=(tmp[i].y<<(6*i+3));
}
return res;
}

int bfs( int kind,node2 now ){
queue<node2>q;
node2 p,pp;
p=now,p.t=0;
if( kind==2 ){
it=mp.find( get_hash(p.pos) );
if( it!=mp.end() )
return p.t;
}
mp[ get_hash(p.pos) ]=kind;
q.push( p );
while( !q.empty() ){
p=q.front(),q.pop();
if( p.t>=4 )
continue;
for( int i=0;i<4;i++ ){
for( int j=0;j<4;j++ ){//j is dir
pp=p;//this is important
pp.pos[i].x=p.pos[i].x+dx[j];
pp.pos[i].y=p.pos[i].y+dy[j];
pp.t=p.t+1;
if( out2( pp )==true )
continue;
if( exist( pp,i )==true ){
pp.pos[i].x+=dx[j];
pp.pos[i].y+=dy[j];
if( out2(pp)==true )
continue;
if( exist( pp,i )==false ){
int my_hash=get_hash( pp.pos );
it=mp.find( my_hash );
if( kind==1 ){
if( it==mp.end() ){
mp[ my_hash ]=kind;
q.push( pp );
}
}
else{
if( it==mp.end() ){
mp[ my_hash ]=kind;
q.push( pp );
}
else if( (*it).second==1 )
return pp.t;
}
}//第二步 不存在某个点
}//第一步 已经存在某个点
else{
int my_hash=get_hash( pp.pos );
it=mp.find( my_hash );
if( it==mp.end() ){
mp[ my_hash ]=kind;
q.push( pp );
}//1 2 all should put into the queue
if( kind==2 ){
if( it!=mp.end() )
if( (*it).second==1 )
return pp.t;
}
}
}
}
}
return -1;
}

int main(){
while( scanf("%d%d",&s.pos[0].x,&s.pos[0].y )==2 ){
s.pos[0].x--,s.pos[0].y--;
for( int i=1;i<4;i++ ){
scanf("%d%d",&s.pos[i].x,&s.pos[i].y);
s.pos[i].x--,s.pos[i].y--;
}
for( int i=0;i<4;i++ ){
scanf("%d%d",&e.pos[i].x,&e.pos[i].y);
e.pos[i].x--,e.pos[i].y--;
}
mp.clear();
bfs( 1,s );//kind ,now node2;
int flag=bfs( 2,e );
if( flag==-1 )
printf("NO\n");
else
printf("YES\n");
}
return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: