(UVA) The ? 1 ? 2 ? ... ? n = k problem

来源:互联网 发布:cam是什么软件 编辑:程序博客网 时间:2024/05/21 15:48

 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 = 12with 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

212-3646397

Sample Output

72701

Alex Gevak
September 15, 2000 (Revised 4-10-00, Antonio Sanchez)

题意:通过在1到x之间添加+或者-运算,使得最后的结果等于n,输出最小的x的
值。最初想着使用BFS,提交时TLE,因为n的值太大,看到别人用到的一种数学做
法,很简单。
思路:通过1到i相加得到的和sum大于等于n,自i开始求(sum-n)%2 == 0 ,等式
不成立时sum = sum + i (i++),等式成立时输出i的值,这是的i就是要求的值。
因为sum存的是1到i的和,如果在i的时候出现“-”号 就相当于在n的基础上加了2个
i,所以差值被2整除的值所对应的就是要求的值。

#include<stdio.h>#include<string.h>#include<stdlib.h>int main(){    int T;    scanf("%d",&T);    long long int n;    while(T--)    {        long long int sum = 0;        scanf("%lld",&n);        if(n<0)        {            n = -n;        }        int ii  = 0;        for(int i=1;;i++)        {            sum += i;            if(sum >= n)            {                ii = i;                break;            }        }        if((sum - n)%2 == 0)        {            if(T>0)            {                printf("%d\n\n",ii);            }            else            {                printf("%d\n",ii);            }            continue;        }        for(int j=ii+1;;j++)        {            sum += j;            if((sum-n)%2 == 0)            {                if(T>0)                {                    printf("%d\n\n",j);                }                else                {                    printf("%d\n",j);                }                break;            }        }    }    return 0;}



0 0
原创粉丝点击