CF11B Jumping Jack 题解
题目
链接
https://www.luogu.com.cn/problem/CF11B
字面描述
题面翻译
题目简述
从原点开始移动,目标为点 x x x 。第 n n n 次移动 n n n 个单位。每次皆可以向左、右两个方向跳跃,求到达 x x x 所需要的最少移动次数。
输入仅一行,一个整数 x x x ( − 1 0 9 ≤ x ≤ 1 0 9 ) (-10^9\leq x\leq 10^9) (−109≤x≤109) 。
输出到达 x x x 所需要的最少移动次数。
@Aw顿顿 感谢您提供的翻译
题目描述
Jack is working on his jumping skills recently. Currently he’s located at point zero of the number line. He would like to get to the point $ x $ . In order to train, he has decided that he’ll first jump by only one unit, and each subsequent jump will be exactly one longer than the previous one. He can go either left or right with each jump. He wonders how many jumps he needs to reach $ x $ .
输入格式
The input data consists of only one integer $ x $ ( $ -10{9}<=x<=10{9} $ ).
输出格式
Output the minimal number of jumps that Jack requires to reach $ x $ .
样例 #1
样例输入 #1
2
样例输出 #1
3
样例 #2
样例输入 #2
6
样例输出 #2
3
样例 #3
样例输入 #3
0
样例输出 #3
0
思路
本道题是一个数轴,到达的点 x ( − 1 0 9 ⩽ x ⩽ 1 0 9 ) x(-10^9\leqslant x \leqslant 10^9) x(−109⩽x⩽109),通过 n n n次,第 i i i次 ± i \plusmn i ±i
根据胡老师名言:“研究数,要从绝对值和符号分别考虑”
但这道题 i i i的双向变化,我们就不需要考虑符号,只需要考虑向哪个方向移动。
为了保证
n
n
n最小我们要一直让
c
n
t
+
i
cnt+i
cnt+i,如果恰好
c
n
t
=
x
cnt=x
cnt=x,
∴
p
r
i
n
t
(
i
)
\therefore print (i)
∴print(i)
否则我们一直加,如果
c
n
t
>
x
cnt>x
cnt>x ,我们肯定要折返需要一步
−
c
n
t
−
x
2
-\frac{cnt-x}{2}
−2cnt−x,
这时候要分情况讨论,若
c
n
t
−
x
≡
0
(
m
o
d
2
)
)
cnt-x \equiv 0 \pmod 2)
cnt−x≡0(mod2)) 则输出
i
i
i
否则这道题不能减分数,则
c
o
n
t
i
n
u
e
continue
continue
代码实现
#include<bits/stdc++.h>
using namespace std;
int n,cnt;
int main(){
scanf("%d",&n);
n=abs(n);
for(int i=1;i<=1e5;i++){
if(cnt>=n&&(cnt-n)%2==0){
printf("%d\n",i-1);
break;
}
cnt+=i;
}
return 0;
}
后继
感谢观看