您的位置:首页 > 其它

hdu 1195 双向bfs

2015-06-19 18:07 253 查看
http://acm.hdu.edu.cn/showproblem.php?pid=1195

这代码好长,不过好多重复的内容。

#include <iostream>
#include <queue>
#include <cstring>
using namespace std;
struct node
{
int x, step;
};
int vis[10000];
node q1[10000];
node q2[10000];
int c[5],d[5];
int ss[2]={1,-1};
void hash1(int x)
{
for(int i = 3; i>=0; i--)
{
c[i] = x%10;
x/=10;
}
}
int rehash()
{
int a = 0;
for(int i = 0; i<4; i++)
a = a*10+d[i];
return a;
}
int front1,front2,tail1,tail2,tmp;
int bfs(int a, int b)
{
front1=front2=tail1=tail2=0;
node temp;
temp.x=a;
temp.step=0;
q1[tail1++] = temp;
temp.x=b;
temp.step=0;
q2[tail2++]=temp;
vis[a]=1;
vis[b]=2;
while(front1<tail1||front2<tail2)
{
tmp = tail1;
for(; front1<tmp; front1++)
{
temp = q1[front1];
hash1(temp.x);
for(int k = 0; k<2; k++)
{
for(int i = 0; i<4; i++)
{
for(int j = 0; j<4; j++)
d[j]=c[j];
d[i]+=ss[k];
if(k==0&&d[i]>9)
d[i] = 1;
else if(k==1&&d[i]<1)
d[i] = 9;
int ans = rehash();
if(vis[ans]!=1)
{
if(vis[ans]==2)
{
int cnt;
for(cnt=1; cnt<tail2; cnt++)
if(q2[cnt].x==ans)
break;
return q2[cnt].step+q1[front1].step+1;
}
vis[ans] = 1;
temp.x = ans;
temp.step = q1[front1].step+1;
q1[tail1++] = temp;
}
}
}
for(int i = 0; i<3; i++)
{
for(int j = 0; j<4; j++)
d[j] = c[j];
int o = d[i];
d[i] = d[i+1];
d[i+1] = o;
int ans = rehash();
if(vis[ans]!=1)
{
if(vis[ans]==2)
{
int cnt;
for(cnt=1; cnt<tail2; cnt++)
if(q2[cnt].x==ans)
break;
return q2[cnt].step+q1[front1].step+1;
}
vis[ans] = 1;
temp.x = ans;
temp.step = q1[front1].step+1;
q1[tail1++] = temp;
}
}
}
tmp = tail2;
for(; front2<tmp; front2++)
{
temp = q2[front2];
hash1(temp.x);
for(int k = 0; k<2; k++)
{
for(int i = 0; i<4; i++)
{
for(int j = 0; j<4; j++)
d[j]=c[j];
d[i]+=ss[k];
if(k==0&&d[i]>9)
d[i] = 1;
else if(k==1&&d[i]<1)
d[i] = 9;
int ans = rehash();
if(vis[ans]!=2)
{
if(vis[ans]==1)
{
int cnt;
for(cnt = 1; cnt<tail1; cnt++)
if(q1[cnt].x==ans)
break;
return q1[cnt].step+q2[front2].step+1;
}
vis[ans] = 2;
temp.x = ans;
temp.step = q2[front2].step+1;
q2[tail2++] = temp;
}
}
}
for(int i = 0; i<3; i++)
{
for(int j = 0; j<4; j++)
d[j] = c[j];
int o = d[i];
d[i] = d[i+1];
d[i+1] = o;
int ans = rehash();
if(vis[ans]!=2)
{
if(vis[ans]==1)
{
int cnt;
for(cnt = 1; cnt<tail1; cnt++)
if(q1[cnt].x==ans)
break;
return q1[cnt].step+q2[front2].step+1;
}
vis[ans] = 2;
temp.x = ans;
temp.step = q2[front2].step+1;
q2[tail2++] = temp;
}
}
}
}
return 0;
}
int main()
{
int t,a,b;
cin>>t;
while(t--)
{
memset(vis,0,sizeof(vis));
cin>>a>>b;
int ans = bfs(a,b);
cout<<ans<<endl;
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: