原题链接.
题意:
在一根无限长的数轴上,你站在0的位置。终点在target的位置。
每次你可以选择向左或向右移动。第 n 次移动(从 1 开始),可以走 n 步。
返回到达终点需要的最小移动次数。
思路:
参考题解
1.因为轴对称,所以到达target与到达target的绝对值一样(到达1和-1的移动次数一样),所以可以把target当做正数处理。
2.假设移动n次,因为移动有两种情况,向右移动即为正,向左移动即为负,所以移动n次都是向右就可以到达的最大距离max = ∑ i = 1 n ( i ) \displaystyle\sum_{i=1}^{n}(i) i=1∑n(i);因为当第i次移动由右变成左,改变后的移动距离比改变前的移动距离少2*i;所以在移动n次的情况下,可以到达的所有位置之间差值是2。
3.举例:
移动次数–可以到达的所有位置
1–1
2–3 1
3–6 4 2 0
4–10 8 6 4 2 0
5–15 13 11 9 7 5 3 1
4.所以有一个step移动次数使得当max>=target且奇偶性一致,step即为所求。
代码:
#include<bits/stdc++.h>
using namespace std;
int main() {
int target;
cin >> target;
if( target<0 ) {
target = -target;
}
int step = 1;
int pos = 0;
while( !(pos>=target||(terget-pos)%2==0) ) {
pos += step;
step++;
}
cout << step-1;
return 0;
}