九度1482解题报告
2014-03-03 21:19
225 查看
http://ac.jobdu.com/problem.php?pid=1482
看到这种题,第一反应就是BFS。可是一开始为剪枝的问题犯愁,最终使用map实现标记已判定的串,其实有点大材小用,只是用到了map.find()的功能,想到其用的是红黑树实现,找起来效率较高,当然别人也有用hash实现的,效率更高,我只是懒得改了。接着就开始为记录树深度犯愁,记得学数据结构的时候,层次遍历是专门修改节点的数据结构来记录树深,但在这里这样做有些麻烦。看了九度鬼M的代码,学会了每次出队时,先记录队长度,然后一次性把原来队里的结点出完,这样队里剩下的都是新拓展出来的下一层的结点。这个方法就方便多了,只需一个while即可,也不用特殊的数据结构。代码如下:
看到这种题,第一反应就是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; }
相关文章推荐
- C++类的继承
- java基本数据类型之间赋值与运算归纳
- Test2
- 只要有你就溫暖了
- jsDocument文档对象
- scuec 1003
- spoj 1029. Matrix Summation(二维树状数组)
- JNI使用:设计综述
- 改变
- Eclipse AmaterasUML 安装及使用
- mac下mysql卸载方法
- Android强制设置横屏或竖屏
- js中location地址对象
- hadoop伪分布式部署及测试
- squid proxy server简单应用 推荐
- 黑马程序员 Java基础学习笔记 集合类
- word无法启动转换器 mswrd632.wpc
- ZOJ 3764 - ZOJ Monthly, March 2014 最大流最小割
- js历史对象History
- python note