A到B的最少步数
A与B地相距n米,一个人第一步只能前进1米或者后退1米,第二步只能前进2米或者后退2米,A走到B最少需要几步
测试用例
输入2 输出3
输入3 输出2
解答
#include <algorithm>
#include <iostream>
#include <queue>
using namespace std;
int main()
{
int dis;
cin >> dis;
int dep = 0;
queue<int> q;
q.push(0);
while (q.size()) {
int sz = q.size();
dep++;
while (sz-- > 0) {
int t = q.front();
q.pop();
for (int i = -1; i <= 1; i += 2) {
int nt = t + dep * i;
if (nt == dis) {
cout << dep<< endl;
return 0;
}
q.push(nt);
}
}
}
return 0;
}