Sum-1844
来源:互联网 发布:sql server中not in 编辑:程序博客网 时间:2024/06/05 16:02
Sum
Time Limit: 1000MS
Memory Limit: 30000KTotal Submissions: 10504
Accepted: 6900
Memory Limit: 30000KTotal Submissions: 10504
Accepted: 6900
Description
Consider the natural numbers from 1 to N. By associating to each number a sign (+ or -) and calculating the value of this expression we obtain a sum S. The problem is to determine for a given sum S the minimum number N for which we can obtain S by associating signs for all numbers between 1 to N.
For a given S, find out the minimum value N in order to obtain S according to the conditions of the problem.
For a given S, find out the minimum value N in order to obtain S according to the conditions of the problem.
Input
The only line contains in the first line a positive integer S (0< S <= 100000) which represents the sum to be obtained.
Output
The output will contain the minimum number N for which the sum S can be obtained.
Sample Input
12
Sample Output
7
Hint
The sum 12 can be obtained from at least 7 terms in the following way: 12 = -1+2+3+4+5+6-7.
Source
这个题就是考你的数学分析能力,把算法搞明白了,那剩下的code就很easy了。
算法分析:
假如:s = 12
sum = 1+2+3+4+5+6+7
sum -1-7之后:
2+3+4+5+6
然后再减去1和7,就是-1+2+3+4+5+6-7=12
我们把sum叫做A,把-1-7叫做X,结果s叫做B
我们发现,如果X存在,那么有这么一个关系式:
A - 2X = B
从而A - B = 2X
也就是说A - B为偶数
看看人家的分析:
1+2+3+4+5+6+7+8+9+10....因为在A中少加一数X(只能有+,-不加必减)相当于A-2X=B;
要让X存在.A-B必为偶数.只要有一数A能减去给出的数B的结果C为偶数的话就一定可了.
sum就是上面说的A,
在例子中的12,输出7。
演示如下:1+2+3+4+5这时为15比12大了但是-12为3(X不能存在)。再加6为21,-12为9(X不能存在)。再加7为28,-12为16,这说明X为8就可以了,在1+2+3+4+5+6+7中要-8就写成-1+2+3+4+5+6-7。又因为28-12=16的16是sum-n的第一个偶数。因此X=8也是第一个合符题意的数。为什么要求要sum-n的第一个偶数吗?上面说了因为在sum中少加一数X(只能有+,- 不加必减)相当于sum-2X=n;X=(sum-n)/2,X必为整数,这就要求(sum-n)能整除2.
代码实现如下:
0 0
- Sum-1844
- POJ 1844 Sum
- poj 1844 Sum
- poj 1844 Sum
- poj 1844 sum
- poj 1844 Sum
- poj 1844 Sum
- POJ 1844 Sum
- POJ 1844 Sum
- 百练 1844 Sum
- poj 1844 sum (数学)
- poj 1844 Sum 【数学】
- poj-1844-Sum
- POJ 1844 Sum
- [POJ]1844 Sum
- POJ 1844 sum
- POJ 1844 Sum 笔记
- Sum
- NMAP 扫描端口速度快
- android 系统优化包括哪些方面
- mongodb查询不重复数据的记录总数
- Jodd瑞士军刀
- html checkbox attr and prop
- Sum-1844
- 模拟按键
- magento 哪些地方应用了EAV模型
- spring AOP切入点表达式规则
- 实时DevExpress内存监视
- JDK源码阅读之List接口
- STL::STRING格式化字符串
- ServletConfig对象详解
- 如何发布Node模块到NPM社区