九度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; }
相关文章推荐
- 数据结构实验之图论二:基于邻接表的广度优先搜索遍历 oj
- SDUT OJ数据结构实验图论一:基于邻接矩阵的广度优先搜索遍历
- 九度OJ 1079 清华真题——字符串处理之《手机键盘》
- 哈理工OJ 1316 移动 II (广度优先搜索+路径打印)
- 九度OJ 1086 动态规划之《最小花费》——11年清华机试真题
- 算法—12.广度优先搜索
- 广度优先搜索练习之神奇的电梯 oj
- 数据结构实验之图论一:基于邻接矩阵的广度优先搜索遍历 oj
- 广度/宽度优先搜索(BFS)
- 深度优先搜索遍历与广度优先搜索遍历
- 广度优先搜索BFS 之图的构造及遍历
- 广度优先搜索.
- 深度优先搜索和广度优先搜索的比较与分析
- 使用广度优先搜索生成关键路径
- 深度优先和广度优先搜索文件
- C++广度优先搜索算法之迷宫问题
- C++广度优先搜索之Knight Moves
- 华容道游戏:广度优先搜索优先搜索
- C++广度优先搜索算法之鸣人与佐助