这是编程设计版本, 来, 程序说话
从坐标0开始交替按等比数列打枪(等待)和右移(追赶)
时刻 坐标 打枪 右移
0 0 1 2
1 2 4 8
5 10 16 32
21 42 64 128
85 170 256 512
....
每一轮的第一枪,(坐标-时刻)是0,1,5,21,85...,是递增的,总能追上右边的蚂蚁
每一轮最后一枪,(坐标-时刻)-1,-3,-11,-43,-171...,是递减的,最后总能被左边蚂蚁追上
#include<iostream>
#include<vector>
#include<cinttypes>
#include<iomanip>
using namespace std;
class Ant {
public:
Ant(long p) {
pos = p;
}
void forWard(long i = 1) {
pos += i;
}
bool hit(long i) {
return i == pos;
}
void print() {
cout << setw(5) << pos;
}
private:
long pos;
};
int main(int argc, char** argv) {
Ant ant(stoll(argv[1]));
long pos = 0;
long time = 0;
long step = 1;
while (step < INT64_MAX/2) {
// shot step bullets on position pos
cout << "time = " << setw(5) << time << ", antPost =";
ant.print();
cout << ", pos = " << setw(5) << pos << ", will Shoot "
<< setw(8) << step << " bullets" << endl;
for (long i = 0; i < step; ++i) {
if (ant.hit(pos)) {
cout << "Bingo! pos = " << pos << ", time = " << time << endl;
exit(0);
}
time++;
ant.forWard();
}
step = step * 2;
pos += step; // gun forward step
step = step * 2;
}
}
看看输出
File Edit Options Buffers Tools Complete In/Out Signals Help
~/code/0730 $ ./a.out 9975
time = 0, antPost = 9975, pos = 0, will Shoot 1 bullets
time = 1, antPost = 9976, pos = 2, will Shoot 4 bullets
time = 5, antPost = 9980, pos = 10, will Shoot 16 bullets
time = 21, antPost = 9996, pos = 42, will Shoot 64 bullets
time = 85, antPost =10060, pos = 170, will Shoot 256 bullets
time = 341, antPost =10316, pos = 682, will Shoot 1024 bullets
time = 1365, antPost =11340, pos = 2730, will Shoot 4096 bullets
time = 5461, antPost =15436, pos = 10922, will Shoot 16384 bullets
time = 21845, antPost =31820, pos = 43690, will Shoot 65536 bullets
Bingo pos = 43690, time = 33715
~/code/0730 $ ./a.out -45738
time = 0, antPost =-45738, pos = 0, will Shoot 1 bullets
time = 1, antPost =-45737, pos = 2, will Shoot 4 bullets
time = 5, antPost =-45733, pos = 10, will Shoot 16 bullets
time = 21, antPost =-45717, pos = 42, will Shoot 64 bullets
time = 85, antPost =-45653, pos = 170, will Shoot 256 bullets
time = 341, antPost =-45397, pos = 682, will Shoot 1024 bullets
time = 1365, antPost =-44373, pos = 2730, will Shoot 4096 bullets
time = 5461, antPost =-40277, pos = 10922, will Shoot 16384 bullets
time = 21845, antPost =-23893, pos = 43690, will Shoot 65536 bullets
time = 87381, antPost =41643, pos = 174762, will Shoot 262144 bullets
Bingo pos = 174762, time = 220500
【 在 stub 的大作中提到: 】
: 有一个无限长的整数刻度的坐标轴,有一只蚂蚁在某一个整数刻度上,但是具体位置未知,现在蚂蚁每秒钟都会向正方向前进一格。你有一把手枪,每秒钟你能向坐标轴的某个刻度开一枪,之后只能知道打中还是没打中,请你设计一种开枪的策略,保证最终一定能打中这只蚂蚁。
--
FROM 183.194.168.*