码迷,mamicode.com
首页 > 其他好文 > 详细

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

时间:2015-01-16 14:49:24      阅读:156      评论:0      收藏:0      [点我收藏+]

标签:

 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

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;
}



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

标签:

原文地址:http://blog.csdn.net/yeguxin/article/details/42775815

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!