您的位置:首页 > 其它

九度OJ 清华12真题之广度优先搜索之《玛雅密码》

2013-03-12 16:42 316 查看
题目地址:http://ac.jobdu.com/problem.php?pid=1482

#include<stdio.h>
#include<string.h>
#include<queue>
#define MAXS 20
using namespace std;
bool mark[1594330];
int mark2[3];
int l,n;
typedef struct E{
int h[MAXS];
int num;//映射成三进制的十进制以便harsh
int count;//记录转换次数
void change()//转换成三进制数- -!
{
num=0;
int i,j;
for(i=0,j=1;i<n;i++,j*=3)num+=h[i]*j;
}
}E;
E a,temp;
queue < E > Q;
bool check(E x)
{
int i;
for(i=0;i<n;i++)//因为数组后面全是0。所以判定条件不用i<n-3。因为到最后必然false。
{
if(x.h[i]==2&&x.h[i+1]==0&&x.h[i+2]==1&&x.h[i+3]==2)return true;
}
return false;
}
int main()
{
int i,j,ans;//ans记录一共的次数
char temph[MAXS];
while(~scanf("%d",&n))
{
mark2[0]=mark2[1]=mark2[2]=ans=0;
memset(mark,0,sizeof(mark));
memset(&a,0,sizeof(a));
while(Q.empty()==false)Q.pop();
getchar();
scanf("%s",temph);
for(i=0;i<n;i++){a.h[i]=temph[i]-'0';mark2[a.h[i]]++;}
if(mark2[2]<2||mark2[0]<1||mark2[1]<1){printf("-1\n");continue;}
a.change();
mark[a.num]=true;
a.count=0;
Q.push(a);
if(check(a)){printf("0\n");continue;}
while(!ans)
{
a=Q.front();Q.pop();a.count++;
for(i=1;i<n;i++)//i标记需要交换的数的后面那个位置
{
temp=a;
int tempi=temp.h[i];//交换这俩值
temp.h[i]=temp.h[i-1];
temp.h[i-1]=tempi;
temp.change();
if(check(temp)==true){ans=temp.count;break;}
if(mark[temp.num])continue;
mark[temp.num]=true;
Q.push(temp);
}
}
printf("%d\n",ans);
}
return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: