Acm学习总结13
这次是关于学习搜索的总结,这是我近期做的别人觉得比较简单的bfs的题目。
一个农夫抓逃走的牛的题目:
#include
#inlcude
#include
using namespace std;
const int N = 1000000;
int map[N+10];
int n,k;
struct node
{
int x,step;
};
int check(int x)
{
if(x<0 || x>=N || map[x])
return 0;
return 1;
}
int bfs(int x)
{
int i;
queue Q;
node a,next;
a.x = x;
a.step = 0;
map[x] = 1;
Q.push(a);
while(!Q.empty())
{
a = Q.front();
Q.pop();
if(a.x == k)
return a.step;
next = a;
//每次都将三种状况加入队列之中
next.x = a.x+1;
if(check(next.x))
{
next.step = a.step+1;
map[next.x] = 1;
Q.push(next);
}
next.x = a.x-1;
if(check(next.x))
{
next.step = a.step+1;
map[next.x] = 1;
Q.push(next);
}
next.x = a.x*2;
if(check(next.x))
{
next.step = a.step+1;
map[next.x] = 1;
Q.push(next);
}
}
}
int main()
{
int ans;
while(cin>>n>>k)
{
memset(map,0,sizeof(map));
ans = bfs(n);
cout<<ans<<endl;
}
return 0;
}
关于dfs的题目我总结了一些经常出现的问题一般就是有时候设置终止的条件设置错了超出了边界或者是没有再一次运算之后没有恢复现场,下一会的回溯出现了错误;
这是一道使用dfs算法比较好理解的一道题
设有A,B,C,D,E五人从事J1,J2,J3,J4,J5五项工作,每人只能从事一项,他们的效益如下
每人选择五项工作中的一项,在各种选择的组合中,找到效益最高的的一种组合输出。
#include
#include
#include
using namespace std;
int data[6][6]={{0,0,0,0,0,0},{0,13,11,10,4,7},{0,13,10,10,8,5},{0,5,9,7,7,4},{0,15,12,10,11,5},{0,10,11,8,8,4}};//这是把表的所有情况输入进去;
int max1=0,g[10],f[10];
bool p[6]={0};
int go(int step,int t) // step是第几个人,t是之前已得的效益
{
for (int i=1;i<=5;i++)
if (!p[i]) //判断第i项工作没人选择,如果有人选择了这个就是1;
{
f[step]=i; //第step个人,就选第i项工作
p[i]=1; //标记第i项工作被人安排了
t+=data[step][i]; //计算效益值
if (step<5) go(step+1,t);
else if (t>max1) //保存最佳效益值
{
max1=t;
for (int j=1;j<=5;j++)
g[j]=f[j]; //保存最优效益下的工作选择方案
}
t-=data[step][i]; //回溯
p[i]=0;恢复现场;
}
}
这次的总结也就是这些了;