您的位置:首页 > 其它

九度1482解题报告

2014-03-03 21:19 225 查看
http://ac.jobdu.com/problem.php?pid=1482

看到这种题,第一反应就是BFS。可是一开始为剪枝的问题犯愁,最终使用map实现标记已判定的串,其实有点大材小用,只是用到了map.find()的功能,想到其用的是红黑树实现,找起来效率较高,当然别人也有用hash实现的,效率更高,我只是懒得改了。接着就开始为记录树深度犯愁,记得学数据结构的时候,层次遍历是专门修改节点的数据结构来记录树深,但在这里这样做有些麻烦。看了九度鬼M的代码,学会了每次出队时,先记录队长度,然后一次性把原来队里的结点出完,这样队里剩下的都是新拓展出来的下一层的结点。这个方法就方便多了,只需一个while即可,也不用特殊的数据结构。代码如下:

#include <stdio.h>
#include <string>
#include <map>
#include <memory.h>
#include <queue>
using namespace std;

map <string,int> m;
int size;
queue <string> q;

int count(string s, string c)
{
int ret=0, t=s.find(c,0);
while (t!=string::npos)
{
++ret;
t=s.find(c,t+1);
}
return ret;
}

int BFS(string a, int n)
{
string tar("2012");
q.push(a);
int ret=0;
while (!q.empty())
{
int qsize=q.size();
while (qsize--)
{
a=q.front();
q.pop();
if (m.find(a)==m.end())
{
m[a]=size++;
if (a.find(tar,0)!=string::npos) return ret;
for (int i=0;i<n-1;++i)
{
string stemp=a;
char temp=stemp[i];
stemp[i]=stemp[i+1];
stemp[i+1]=temp;
q.push(stemp);
}
}
}
++ret;
}
return -1;
}

int main()
{
int n;
char s[15];
while (scanf("%d",&n)!=EOF)
{
char c=getchar();
scanf("%s",s);
m.clear();
size=0;
while (!q.empty()) q.pop();
string a=s;
string c0("0"), c1("1"), c2("2");
int cnt0=count(s,c0);
int cnt1=count(s,c1);
int cnt2=count(s,c2);
if (cnt0<1||cnt1<1||cnt2<2)
{
printf("-1\n");continue;
}
printf("%d\n",BFS(a,n));
}
return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: