题目链接:http://www.lydsy.com/JudgeOnline/problem.php?id=1646

这道题我刚开始就直接硬生生地广搜,然后妥妥地TLE了,后来乖乖地加了一些剪枝。。。

具体程序里看吧,反正就是典型的广搜,但是有一些细节

程序:

#include<iostream>
#include<cstdio>
#include<cstring>
#include<queue>
using namespace std;
queue< pair<int,int> >q;
int n,k;
bool f[2000000];
bool check(int x)
{
  if ((x<0)||(x>100000)) return false;
//检查这个点是不是已经超范围了
  if (f[x]) return false;
//哈这个很重要,如果已经如果队列了,就没必要再进一遍
  return true;
}
int main()
{
  scanf("%d%d",&n,&k);
  q.push(make_pair(n,0));
  while (!q.empty())
  {
    pair<int,int> now=q.front(); q.pop();
    if (now.first==k)
    {
       printf("%d",now.second);
       return 0;
    }
    if (now.first<k)
    {
      if (check(now.first*2)) 
      {
        q.push(make_pair(now.first*2,now.second+1));
        f[now.first*2]=true;
      }
      if (check(now.first+1)) 
      {
        q.push(make_pair(now.first+1,now.second+1));
        f[now.first+1]=true;
      }
      if (check(now.first-1))
      {
        q.push(make_pair(now.first-1,now.second+1));
        f[now.first-1]=true;
      }
    }
//如果这个点已经超过目标点了,它只能一步步往回挪了
    if ((now.first>k)&&(check(now.first-1))) 
    {
      q.push(make_pair(now.first-1,now.second+1));
      f[now.first-1]=true;
    }
  }
  return 0;
} 

 

posted on 2017-04-03 01:24  nhc2014  阅读(197)  评论(0编辑  收藏  举报