10025 - The ? 1 ? 2 ? ... ? n = k problem
Time limit: 3.000 seconds
The ? 1 ? 2 ? ... ? n = k problem
The problem
Given the following formula, one can set operators '+' or '-' instead of each '?', in order to obtain a given k
? 1 ? 2 ? ... ? n = k
For example: to obtain k = 12 , the expression to be used will be:
- 1 + 2 + 3 + 4 + 5 + 6 - 7 = 12
with n = 7
The Input
The first line is the number of test cases, followed by a blank line.
Each test case of the input contains integer k (0<=|k|<=1000000000).
Each test case will be separated by a single line.
The Output
For each test case, your program should print the minimal possible n (1<=n) to obtain k with the above formula.
Print a blank line between the outputs for two consecutive test cases.
Sample Input
2 12 -3646397
Sample Output
7
2701 题意:±1 ± 2 ± 3 ±…± n = k , 找出满足条件的最小 n 。。
这题做的时间跨越好久啊,今天看了无数的解题报告终于小懂了。(没有优化)
必然存在整数 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的差必为偶数,剩下的暴力找就可以了。
通过求和公式,求出前n个和比k大的n的最小值,然后判断前n个数的和与k的值的差是否为偶数,如果为偶数则表示该n为最小的所需个数,因为如果差为偶数,则只需将前n个数的几个数前的符号改为减号,就可以得到k,如果不为偶数,则n的值加一,重复以上判断。直到出现符合以上判断的n的出现,则是最小的n的值。
#include<stdio.h>
#include<math.h>
int main()
{
int t;
int flag=0;
scanf("%d",&t);
while(t--)
{
int k;
scanf("%d",&k);
if(flag>0)
printf("\n");
flag++;
if(k<0)//正负的处理是一样的
k=-k;
int sum=0;
for(int i=1;;i++)
{
sum+=i;
if(sum>=k&&(sum-k)%2==0)
{
printf("%d\n",i);
break;
}
}
}
return 0;
}