codeforces 11B Jumping Jack

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.

Input

The input data consists of only one integer x ( - 109 ≤ x ≤ 109).

Output

Output the minimal number of jumps that Jack requires to reach x.

Example

Input
2
Output
3
Input
6
Output
3
Input
0
Output
0

这题想的很僵硬,想了一个小时才想出来。
题意:步数从1开始递增,只能选择向左走和向右走。问到达x最少要走几次。
解题思路:可以很轻易的(我推了半小时才反应过来)的想出 x=1±2±3±...n;
对吧,因为不是向左走就是向右走嘛,所以不是加就是减。
这样我们可以推出x肯定在1到1+2+3+...n之间(包括n。
所以我们找第一个大于等于x的 1~n和,如果刚好等于就直接输出步数。
如果大于x,就找第一个大于x且与x差为偶数的数。(这需要一点脑洞
因为x+n与x-n的差肯定是个偶数,而1~n的和包含了从2,4,6,8一直到n的所有偶数,所以只要找到离x最近的差为偶数的 1~n和,就是答案了。

说的比较乱,不懂的话可以自己写1到10的例子走一下就明白了。

附ac代码:
 1 #include <cstdio>
 2 #include <iostream>
 3 #include <cmath>
 4 #include <string>
 5 #include <cstring>
 6 #include <algorithm>
 7 #include <queue>
 8 #include <map>
 9 #include <vector>
10 using namespace std;
11 const int maxn = 1e6+10;
12 typedef long long ll;
13 const ll mod = 1e9+7;
14 const int inf = 0x3f3f3f3f;
15 const double eps=1e-6;
16 ll ans[maxn];
17 ll l[maxn];
18 ll r[maxn];
19 int main() {
20     ios::sync_with_stdio(false);
21     int n;
22     cin>>n;
23     n=abs(n);
24     if(n==0)
25     {
26         cout<<0<<endl;
27         return 0;
28     }
29     for(int i=1;i<=1e9;++i)
30     {
31         ll s=i*(i+1)/2;
32         if(s==n)
33         {
34             cout<<i<<endl;
35             break;
36         }
37         else if(s>n &&(s-n)%2==0)
38         {
39             cout<<i<<endl;
40             break;
41         }
42     }
43     return 0;
44 }
View Code

 



posted @ 2018-02-01 13:18  euzmin  阅读(319)  评论(0编辑  收藏  举报