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) (109x109)

输出到达 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(109x109),通过 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} 2cntx,
这时候要分情况讨论,若 c n t − x ≡ 0 ( m o d 2 ) ) cnt-x \equiv 0 \pmod 2) cntx0(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;
} 

后继

感谢观看

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

materialistOier

我只是一名ssfoier

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值