Time Limit: 2000MS | Memory Limit: 65536K | |
Total Submissions: 90830 | Accepted: 28508 |
Description
Farmer John has been informed of the location of a fugitive cow and wants to catch her immediately. He starts at a point N (0 ≤ N ≤ 100,000) on a number line and the cow is at a point K (0 ≤ K ≤ 100,000) on the same number line. Farmer John has two modes of transportation: walking and teleporting.
* Walking: FJ can move from any point X to the points X - 1 or X + 1 in a single minute
* Teleporting: FJ can move from any point X to the point 2 × X in a single minute.
If the cow, unaware of its pursuit, does not move at all, how long does it take for Farmer John to retrieve it?
Input
Output
Sample Input
5 17
Sample Output
4
Hint
Source
for(i=start;i>0;i--)
dp[i-1]=dp[i]+1;
/*DP*/
#include<iostream>
#include<cstring>
#include<queue>
using namespace std;
const int MAX = 1e5+5;
int start,target;
int now ,pos;
int dp[MAX];
int i;
int main()
{
cin >> start >> target;
for(i=start;i>0;i--)
dp[i-1]=dp[i]+1;
for(i=start+1;i<=target;i++)
{
dp[i]=dp[i-1]+1;
if (i%2==1) dp[i]=min(dp[i],dp[i/2+1]+2);
else
dp[i]=min(dp[i],dp[i/2]+1);
}
cout << dp[target] <<endl;
return 0;
}
/*BFS*/
#include<iostream>
#include<cstring>
#include<queue>
using namespace std;
const int MAX=1E5+10;
static bool visit[MAX]={false};
static int step[MAX]={0};
int now,position;
int first,finally;
queue <int> que;
int BFS(int n)
{
que.push(n);
while(!que.empty())
{
now=que.front();
que.pop();
for(int i=0;i<3;i++)
{
if (i==0) position=now-1;
else if(i==1) position=now+1;
else position=2*now;//now 當前位置 position 經過一步移動後的位置
if(visit[position]==false&&position>=0&&position<=MAX)
{
visit[position]=true;
step[position]=step[now]+1;
que.push(position);
}
if(position==finally)
return step[position];
}
}
}
int main()
{
cin >> first >> finally;
while(!que.empty()) que.pop();
memset(visit,false,sizeof(visit));
memset(step,0,sizeof(step));
if (first>=finally) cout << first-finally <<endl;
else
cout << BFS(first) << endl;
return 0;
}