您的位置:首页 > 其它

UVa 10025 - The ? 1 ? 2 ? ... ? n = k problem

2012-08-14 21:12 501 查看
必然存在整数 x(1=< x <= n)满足:

当 s1 = 1+2+3+...+x+..+n >= k时,有 s2 = 1+2+3+...-x+..+n == k,即多出的x肯定在1~n之间。

s1 - s2 = s1 - k = 2x

所以,我们想求最小的n,也就是求最小的满足条件的s1,而它与k的差必为偶数,剩下的暴力找就可以了。

#include<iostream>

#include<string>

#include<cstring>

#include<cstdio>

#include<queue>

#include<stack>

#include<algorithm>

#include<cmath>

using namespace std;

int main()

{

int k,n,s;

int t;

while(scanf("%d",&t) != EOF)

{

while(t--)

{

scanf("%d",&k);

if(k<0)k=-k;

if(k==0)puts("3");

else

{

n = s = 0;

while(s < k)s += ++n;

while((s-k)&1) s += ++n;

printf("%d\n",n);

}

if(t)putchar('\n');

}

}

return 0;

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: