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

 

必然存在整数 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;

}

posted @ 2012-08-14 21:12  godjob  Views(341)  Comments(0Edit  收藏  举报