您的位置:首页 > 其它

HDU 1401 双广

2014-02-20 14:48 120 查看
#include <iostream>
#include <cstring>
#include <cmath>
#include <cstdio>
#include <algorithm>
#include <cstdlib>
#include <queue>
#include <set>
using namespace std;
int pos[4]={1,10,-1,-10};
struct str
{
int x,step;
}t1,t2;

int get_st(int x)
{
int a[4],i,ans=0;
for(i=0;i<4;i++)
{
a[i]=x%100;
x/=100;
}
sort(a,a+4);
for(i=0;i<4;i++) ans=ans*100+a[i];
return ans;
}

bool can(int x,int q)
{
int i=4,ans=0;
while(i--)
{
if(x==q%100) ans++;
q/=100;
}
return ans==1;
}

bool can(int q)
{
int i=4,x=q;
while(i--)
{
if(!can(x%100,q)) return 0;
x/=100;
}
i=8;
while(i--)
{
if(q%10>=8) return 0;
q/=10;
}
return 1;
}

int main()
{
while(cin>>t1.x)
{
t1.x--;
int i,j,k;
for(i=1;i<8;i++)
{
cin>>k;
k--;
t1.x=t1.x*10+k;
}
t2.x=0;
for(i=0;i<8;i++)
{
cin>>k;
k--;
t2.x=t2.x*10+k;
}
queue<str> q;
set<int> st;
str tail=t1,head;
tail.step=0;
q.push(tail);
st.insert(get_st(tail.x));
while(q.size())
{
head=q.front();
if(head.step>=4) break;
k=1;
for(i=0;i<4;i++,k*=100)
{
for(j=0;j<4;j++)
{
tail.step=head.step+1;
tail.x=head.x+pos[j]*k;
if(can(tail.x))
{
q.push(tail);
st.insert(get_st(tail.x));
}
else
{
tail.x+=pos[j]*k;
if(can(tail.x))
{
q.push(tail);
st.insert(get_st(tail.x));
}
}
}
}
q.pop();
}
while(q.size()) q.pop();
int ans=0;
t2.step=0;
q.push(t2);
while(q.size() && ans==0)
{
head=q.front();
if(head.step>=4) break;
if(st.count(get_st(head.x)))
{
ans=1;
//cout<<head.x<<endl;
break;
}
k=1;
for(i=0;i<4 && ans==0;i++,k*=100)
{
for(j=0;j<4 && ans==0;j++)
{
tail.step=head.step+1;
tail.x=head.x+pos[j]*k;
if(can(tail.x))
{
q.push(tail);
if(st.count(get_st(tail.x)))
{
ans=1;
break;
}
}
else
{
tail.x+=pos[j]*k;
if(can(tail.x))
{
q.push(tail);
if(st.count(get_st(tail.x)))
{
ans=1;
break;
}
}
}
}
}
q.pop();
}
if(ans) puts("YES");
else puts("NO");
}
return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: