• Max Sum--hdoj 1003 dp


    Max Sum

    Time Limit: 2000/1000 MS (Java/Others)    Memory Limit: 65536/32768 K (Java/Others)
    Total Submission(s): 181284    Accepted Submission(s): 42384


    Problem Description
    Given a sequence a[1],a[2],a[3]......a[n], your job is to calculate the max sum of a sub-sequence. For example, given (6,-1,5,4,-7), the max sum in this sequence is 6 + (-1) + 5 + 4 = 14.
     

    Input
    The first line of the input contains an integer T(1<=T<=20) which means the number of test cases. Then T lines follow, each line starts with a number N(1<=N<=100000), then N integers followed(all the integers are between -1000 and 1000).
     

    Output
    For each test case, you should output two lines. The first line is "Case #:", # means the number of the test case. The second line contains three integers, the Max Sum in the sequence, the start position of the sub-sequence, the end position of the sub-sequence. If there are more than one result, output the first one. Output a blank line between two cases.
     

    Sample Input
    2 5 6 -1 5 4 -7 7 0 6 -1 1 -6 7 -5
     

    Sample Output
    Case 1: 14 1 4 Case 2: 7 1 6
     



    /*找出一个数组中和最大的一串数字,求和并输出起点和终点,简单的dp,一个数字一个数字开始加
    找到小于0的话就重新开始找,否则就继续加,开始时想用01背包做,但是发现全部的数字加起来可能是
    负数,这样的话01背包就没办法列出所有的情况,并且起点和终点也不好记录*/
    #include<stdio.h>
    #include<string.h>
    int a[100010];
    int main()
    {
    	int max,b,e,t,n,sum;
    	int Case=1;
    	scanf("%d",&t);
    	while(t--)
    	{
    		scanf("%d",&n);
    		memset(a,0,sizeof(a));
    		for(int i=1;i<=n;i++)
    		scanf("%d",&a[i]);
    		int k=1;
    		int max=0,flog=0;
    		sum=b=e=0;
    		for(int j=1;j<=n;j++)
    		{
    			if(a[j]>0)
    			flog=1;//如果数组中没有一个数大于0,那么就找出最大的负数 
    			sum+=a[j];
    			if(sum<0)
    			{
    				sum=0;
    				k=j+1;//如果sum<0,就让sum=0重新开始加 
    			}	
    			if(sum>max)
    			{
    				max=sum;//找到比max大的和就开始替换 
    				b=k;
    				e=j;
    			}
    		}
    		if(flog==0)
    		{
    			max=a[1];
    			b=1,e=1;
    			for(int j=2;j<=n;j++)
    			if(max<a[j])
    			{
    				max=a[j];
    				b=j;e=j;
    			}
    		}
    		printf("Case %d:
    ",Case++);
    		printf("%d %d %d
    ",max,b,e);
    		if(t>=1)
    		printf("
    ");
    	}
    	return 0;
    }
     
  • 相关阅读:
    destroy-method="close"
    2.2 Spring的结构组成--Spring源码深度解析
    2.1 Spring容器的基本实现--Spring源码深度解析
    1.2 Spring环境搭建--Spring源码深度解析
    1.1 Spring的整体架构--Spring源码深度解析
    迟到的2016年计划
    spring学习 之helloworld
    从零实现DNN 探究梯度下降的原理
    Java注解——这些@圈圈都是个啥?
    自动发送日报,骗过你的领导^-^
  • 原文地址:https://www.cnblogs.com/playboy307/p/5273808.html
Copyright © 2020-2023  润新知