ppoj 3278搜索bfs+剪枝

http://poj.org/problem?id=3278

大致题意:

给定两个整数n和k

通过 n+1或n-1 或n*2 这3种操作,使得n==k

输出最少的操作次数

 

解题思路:

说实话,要不是人家把这题归类到BFS,我怎么也想不到用广搜的= = 自卑ing。。。

 

水题水题,三入口的BFS

 

注意的地方有二:

1、  由于用于广搜的 队列数组 和 标记数组  相当大,如果定义这两个数组时把它们扔到局部去,编译是可以的,但肯定执行不了,提交就等RE吧= =

大数组必须开为 全局 。。。常识常识。。。

2、  剪枝。直接广搜一样等着RE吧= =

不剪枝的同学试试输入n=0  k=100000。。。。。。铁定RE

怎么剪枝看我程序

 

 

 1 /*
 2 给定两个整数n和k
 3 通过 n+1或n-1 或n*2 这3种操作,使得n==k
 4 输出最少的操作次数*/
 5 #include<iostream>
 6 #include<cstdio>
 7 #include<cstring>
 8 #include<queue>
 9 using namespace std;
10 int map[200005];
11 bool dis[200005];
12 int n,k,temp;
13 int bfs()
14 {
15     queue<int>q ;
16     //memset(dis,0,sizeof(dis));
17     //memset(map,0,sizeof(map));
18     q.push(n);
19     map[n]=0;
20 
21     //int temp;
22     //q.pop();
23     while(q.size()!=0)
24     {
25         temp=q.front();
26         q.pop();
27         dis[n]=1;
28         if(temp==k)
29         {
30             printf("%d\n",map[temp]);
31             return map[temp];
32         }
33         if((temp-1)>=0&&dis[temp-1]==0)
34         {
35             map[temp-1]=map[temp]+1;
36             dis[temp-1]=1;
37             q.push(temp-1);
38         }
39         if((temp+1)>=0&&dis[temp+1]==0)
40         {
41             map[temp+1]=map[temp]+1;
42             dis[temp+1]=1;
43             q.push(temp+1);
44         }
45         if((temp*2)<=100000&&dis[temp*2]==0)
46         {
47             map[temp*2]=map[temp]+1;
48             dis[temp*2]=1;
49             q.push(temp*2);
50         }
51     }
52 }
53 int main()
54 {
55     //int n,k;
56     scanf("%d%d",&n,&k);
57 bfs();
58    //  printf("%d\n",bfs());
59     //printf("%d\n",map[temp]);
60     return 0;
61 }

 

posted @ 2015-05-18 00:22  zach96  阅读(425)  评论(0编辑  收藏  举报