Catch That Cow
Time Limit: 2000MS | Memory Limit: 65536K | |
Total Submissions: 43761 | Accepted: 13650 |
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
Line 1: Two space-separated integers:
N and
K
Output
Line 1: The least amount of time, in minutes, it takes for Farmer John to catch the fugitive cow.
Sample Input
5 17
Sample Output
4
Hint
The fastest way for Farmer John to reach the fugitive cow is to move along the following path: 5-10-9-18-17, which takes 4 minutes.
【注意】
剪枝
测试数据有多组while(cin>>n>>k)
【解题思路】
这道题目不知道错了多少次。
第一次错误是因为没有剪枝,纯纯的BFS造成内存超出。
后面就是无穷无尽的Runtime error ,是因为数组没有开的足够大,动态数组真心不行,开到100*k+100的大小还是提示RE,真心给跪了。所以还是老老实实开大数组吧。
还有就是题目中说输入只有一行,可是我把while(cin>>n>>k)去掉之后提示wrong answer
三岔路的BFS,但是要剪枝,我做的剪枝方案就是所有的数都要在2*k以内,不要太大了,没有意义。所有的数只允许在队列里出现一次,不然加一减一造成很多浪费
还有就是bool值的new G++编辑器默认给的初始值为false,但是初始化是没人人需要养成的好习惯
【code】
我自己的渣代码
【注意】
剪枝
测试数据有多组while(cin>>n>>k)
【解题思路】
这道题目不知道错了多少次。
第一次错误是因为没有剪枝,纯纯的BFS造成内存超出。
后面就是无穷无尽的Runtime error ,是因为数组没有开的足够大,动态数组真心不行,开到100*k+100的大小还是提示RE,真心给跪了。所以还是老老实实开大数组吧。
还有就是题目中说输入只有一行,可是我把while(cin>>n>>k)去掉之后提示wrong answer
三岔路的BFS,但是要剪枝,我做的剪枝方案就是所有的数都要在2*k以内,不要太大了,没有意义。所有的数只允许在队列里出现一次,不然加一减一造成很多浪费
还有就是bool值的new G++编辑器默认给的初始值为false,但是初始化是没人人需要养成的好习惯
【code】
我自己的渣代码
#include<iostream>
#include<queue>
using namespace std;
int main(void){
int n,k;
while(cin>>n>>k){
queue<int> q;
queue<int> c;
if(n==k){
cout<<'0'<<endl;
continue;
}
bool *in = new bool[1000000];
for(int i =0;i<1000000;i++)in[i]=false;
q.push(n);
in[n]= true;
c.push(0);
while(!q.empty()){
//cout<<"here "<<endl;
int temp = q.front();
int tempc = c.front()+1;
q.pop();
c.pop();
if(temp+1==k||temp-1==k||temp*2==k){
cout<<tempc<<endl;
break;
}
if(temp+1>=0 &&in[temp+1]==false && temp+1<=2*k){
q.push(temp+1);
c.push(tempc);
in[temp+1]=true;
}
if(temp-1>=0 && in[temp-1]==false){
q.push(temp-1);
c.push(tempc);
in[temp-1]=true;
}
if(temp*2>=0 && temp*2<=k*2 && in[temp*2]==false){
q.push(temp*2);
c.push(tempc);
in[temp*2]=true;
}
}
delete[]in;
}
return 0;
}
想找一个效率比较高的代码给大家参考,可惜。。。没找到,大家将就着看吧