首页 > 专题系列 > Java解POJ > POJ 1844 Sum [解题报告] Java
2013
11-10

POJ 1844 Sum [解题报告] Java

Sum

问题描述 :

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.

输入:

The only line contains in the first line a positive integer S (0< S <= 100000) which represents the sum to be obtained.

输出:

The output will contain the minimum number N for which the sum S can be obtained.

样例输入:

12

样例输出:

7

温馨提示:

The sum 12 can be obtained from at least 7 terms in the following way: 12 = -1+2+3+4+5+6-7.

解题代码:

//* @author: [email protected]
import java.util.*;
public class Main
{
 public static void main(String[] args)
 {
  Scanner in=new Scanner(System.in);
  int sun=in.nextInt();
  int sum=0;
  int i;
  for(i=1;i< 9999;i++)
  {
	sum+=i;
	if (sum>=sun)break;
  }
  if((sum-sun)%2==0) System.out.println(i);
  else if((sum-sun)%2==1&&i%2==1) System.out.println(i+2);
  else if((sum-sun)%2==1&&i%2==0) System.out.println(i+1);
 }
}

  1. 其实国内大部分公司对算法都不够重视。特别是中小型公司老板根本都不懂技术,也不懂什么是算法,从而也不要求程序员懂什么算法,做程序从来不考虑性能问题,只要页面能显示出来就是好程序,这是国内的现状,很无奈。

  2. 题本身没错,但是HDOJ放题目的时候,前面有个题目解释了什么是XXX定律。
    这里直接放了这个题目,肯定没几个人明白是干啥

  3. 学算法中的数据结构学到一定程度会乐此不疲的,比如其中的2-3树,类似的红黑树,我甚至可以自己写个逻辑文件系统结构来。