cf#11-B - Jumping Jack-数学
2016-01-29 00:20
176 查看
http://codeforces.com/contest/11/problem/B
Jack在数轴上跳。他第i次跳可以往左或往右跳i个单位。现在问你他最少花多少步跳到点x。
-x的答案显然和x一样,0特判
首先我们让jack跳到第一个大于等于x的地方,走了K步,如果等于,显然结束算法。
如果是大于,我们计算res=当前位置-x,如果res为偶数,显然只要我们之前再步数=res/2的时候,往左跳一步,那么的最后的位置就会比当前少res长度,也就是恰好到达 位置X,总步数K。
如果res为奇数, 那么需要再走多奇数步,凑一个偶数出来, 如果当前步数为偶数,那么下一步就是奇数,只要再走多一步,就回到上面的情况了,总步数K+1。
如果当前步数为奇数,那么只要走多两步即可回到最上面的情况,总步数K+2
Jack在数轴上跳。他第i次跳可以往左或往右跳i个单位。现在问你他最少花多少步跳到点x。
-x的答案显然和x一样,0特判
首先我们让jack跳到第一个大于等于x的地方,走了K步,如果等于,显然结束算法。
如果是大于,我们计算res=当前位置-x,如果res为偶数,显然只要我们之前再步数=res/2的时候,往左跳一步,那么的最后的位置就会比当前少res长度,也就是恰好到达 位置X,总步数K。
如果res为奇数, 那么需要再走多奇数步,凑一个偶数出来, 如果当前步数为偶数,那么下一步就是奇数,只要再走多一步,就回到上面的情况了,总步数K+1。
如果当前步数为奇数,那么只要走多两步即可回到最上面的情况,总步数K+2
#include <cstdio> #include <cstring> #include <algorithm> #include <vector> #include <cmath> #include <iostream> using namespace std; int main() { __int64 x; scanf("%I64d",&x); if (!x) { printf("0\n");return 0;} if (x<0) x=-x; __int64 tmp=0; __int64 ans=1; while(tmp<x) { tmp+=ans;ans++;} ans--; //ans为第一个大于等于与x的数 __int64 res=ans*(ans+1)/2-x ; if (res==0) printf("%I64d\n",ans); else { if (res%2==0) printf("%I64d\n",ans); else { if (ans%2) ans++; printf("%I64d\n",ans+1); } } return 0; } //57283
相关文章推荐
- 从互联网上爬邮箱
- 张五常广州演讲
- Android studio 项目上传至GitHub
- 1个APP的生产过程
- 4. GNU 3DKit
- 机器人运动学
- 喷枪打字效果(实现文字一个一个出现)
- CodeForces 620E New Year Tree(线段树)
- JSPatch – 动态更新iOS APP
- 安装 vs2005, vs2008 报错
- Linux中的两种守护进程stand alone和xinetd
- Java比较002
- 【NYOJ】[100]1的个数
- Codeforces Round #339 (Div. 2) 解题报告
- Java比较001
- centos 7安装ifconfig
- [工作中的设计模式]模板模式
- Chrome扩展开发之三——Chrome扩展中的数据本地存储和下载
- Linux命令之cut详解
- 【Java SE】————JDK、JRE、JVM简介