posts - 195,  comments - 30,  trackbacks - 0

Energy


Status In/Out TIME Limit MEMORY Limit Submit Times Solved Users JUDGE TYPE
stdin/stdout 3s 10240K 717 196 Standard

Mr. Jojer is a very famous chemist. He is doing a research about behavior of a group of atoms. Atoms may have different energy and energy can be positive or negative or zero, e.g. 18 or -9. Absolute value of energy can not be more than 100. Any number of continuous atoms can form an atom-group. Energy of an atom-group is defined by the sum of energy of all the atoms in the group. All the atoms form an atom-community which is a line formed by all the atoms one by one. Energy of an atom-community is defined by the greatest energy of an atom-group that can be formed by atoms in the atom-community. The problem is, given an atom-community, to calculate its energy.

Input

The input contains several test cases. Each test case consists of two lines describing an atom-community. The first line of each test case contains an integer N(N<=1000000), the number of atoms in the atom-community. The second line of each test case contains N integers, separated by spaces, each representing energy of an atom, given in the order according to the atom-community. The last test case marks by N=-1, which you should not proceed.

Output

For each test case(atom-community description), print a single line containing the energy.

Sample Input

5
8 0 6 4 -1
-1

Sample Output

18


理解题意很重要,题目的意思是说 在m个中选   连续的n个atom能量值 使其最大。
程序中sumtemp,sum。sumtemp确定的是其左边界,sum确定其右边界。
sumtemp确定左边前n个数之和为负的最大的n,且第n个数显然为负,然后从n+1开始选数。
sum确定了右边界使其最大。
求和最大都可以用这种思路!!!!!!!!!!
举例
1,2,-4,4,2,-2,1,5,-6,5,-3,8,10
请看sumt1=1,sum=1
sumt2=2;sum=1+2=3;
sum3=sum2-4=-1;则sumtemp=0;sum不变。
sum4=sumtemp+4;sum<sum4,sum=4;
sum5=sumtemp+2;sum<sum5,sum=6
总之sum只有在sum<sumtemp时才修改。sumtemp<0则清0.
一维dp.
#include"stdio.h"
int main()
{
 freopen("s.txt","r",stdin);
  freopen("key.txt","w",stdout);
 int n;
 int a;
 while(scanf("%ld",&n),n!=-1)
 { 
      long long  sum=-0x7fffffff,sumtemp=-0x7fffffff;
   for(long i=0;i<n;i++)
   { 
    scanf("%d",&a);
    if(sumtemp>0)
   sumtemp+=a;
    else
   sumtemp=a;
    if(sumtemp>sum)
   sum=sumtemp;

   }
   printf("%lld\n",sum);

 }
 return 0;
}

posted on 2009-07-04 09:27 luis 阅读(536) 评论(0)  编辑 收藏 引用 所属分类: 动态规划给我启发题贪心*二分

只有注册用户登录后才能发表评论。
网站导航: 博客园   IT新闻   BlogJava   博问   Chat2DB   管理


<2011年11月>
303112345
6789101112
13141516171819
20212223242526
27282930123
45678910

常用链接

留言簿(3)

随笔分类

随笔档案

文章分类

文章档案

友情链接

搜索

  •  

最新评论

阅读排行榜

评论排行榜