首页 > 其他分享 >HDU-1003- Max Sum (动态规划)

HDU-1003- Max Sum (动态规划)

时间:2023-05-21 10:02:33浏览次数:41  
标签:HDU sequence Max num max 序列 1003 maxsum dp





Max Sum


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


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


 



Author


Ignatius.L


 



Recommend


We have carefully selected several similar problems for you:   1176  1087  1069  1058  1203 


 






第一种写法:


这是最常见的一种动态写法,看上去很高端




             0   6   -1  1   -6   7   -5


dp[i]     0   6    5   6   0    7   2


p[i]       0   1    1   1   1    1   1 




            0    -6    -1    1    -6     7    -5 


dp[i]     0    -6    -1    1    -5     7    2


p[i]       0     1     0     0     1     0     1






#include<stdio.h>
#include<iostream>
using namespace std;
#define maxn 100000+10
int num[maxn],dp[maxn],p[maxn];
int main()
{
    int T,n,j;
    scanf("%d",&T);
    for(j=0; j<T; j++)
    {
       int i,sum=0,k=0;
       int start,end;
       cin>>n;
       k++;
       for(i=0;i<n;i++)
          cin>>num[i];
       dp[0]=num[0];
       start=end=1; p[0]=0;
       for(i=1; i<n; i++)
       {
             if(dp[i-1]+num[i]>=num[i]) // 如果前一位置子序列和小雨加上当前位置数据时
             {
                 dp[i]=dp[i-1]+num[i]; //更新当前子序列和
                 p[i]=1;               //  标记当前位置 
          }
          else
          {
              dp[i]=num[i];
              p[i]=0;    //  标记为0 就是子序列的起始位置
          }
       }
       for(i=1; i<n; i++)
       {
             if(dp[i]>dp[0])  // 先找到最大子序列的结束位置
             {
                dp[0]=dp[i];
                end=i+1;   
             }
       }
       start=end;  // 然后从结束位置一次向前找开始位置
       for(i=end; i>=1; i--)
       {
            if(p[i]==1&&p[i-1]==0)   //  如果p[i]=1就继续后退直到 p[i]=0就是这个最大子序列的开始,不懂得可以看上面的模拟数据
            {
                start=i;
                break;
         }
       }
       printf("Case %d:\n%d %d %d\n",j+1,dp[0],start,end);
       if((j+1)!=T) printf("\n");
    }
    return 0;
}








第二种写法:




题目分析:最经典的动态规划,我个人认为动态规划还是比较难理解的,开始接触的时候在网上搜代码几乎都搞不懂。


但是 后来看了一篇博文我才,彻悟!




以a[0]结尾的子序列只有a[0]



以a[1]结尾的子序列有 a[0]a[1]和a[1]



以a[2]结尾的子序列有 a[0]a[1]a[2] / a[1]a[2] / a[2]



……



以a[i]结尾的子序列有a[0]a[1]……a[i-2]a[i-1]a[i]  / a[1]a[2]……a[i-2]a[i-1]a[i] /  a[2]a[3]……a[i-2]a[i-1]a[i] / …… /  a[i-1]a[i] / a[i]






所有以a[0] ~a[n]结尾的子序列分组构成了整个序列的所有子序列。




这样,我们只需求以a[0]~a[n]结尾的这些分组的子序列中的每一分组的最大子序列和。然后从n个分组最大子序列和中选出整个序列的最大子序列和。




观察可以发现,0,1,2,……,n结尾的分组中,


maxsum a[0] = a[0]


maxsum a[1] = max( a[0] + a[1] ,a[1])  =  max( maxsum a[0] + a[1],a[1]) 


maxsum a[2] = max( max ( a[0] + a[1] + a[2],a[1] + a[2] ),a[2])  


= max(  max( a[0] + a[1] ,a[1]), a[2]) 


= max(  maxsum a[1] + a[2] , a[2])


..........................


依此类推,可以得出通用的式子。



maxsum a[i] = max( maxsum a[i-1] + a[i],a[i])      maxsum a[i-1] + a[i] 的意思就是 前一个位置的最大值 maxsum a[i-1] 加上当前位置的数据 a[i] 



我们从maxsum  a[0]开始算起。



以后的每个就是  maxsum a[i-1] + a[i] 和 a[i] 中取大的那个。





如果还不懂:



这里有原文链接可以点击 原文 看一下





#include<stdio.h>
#include<string.h> 
#define INF 0x3f3f3f
int main()
{
	int t,n,a;
	scanf("%d",&t);
	for(int j=1;j<=t;j++)
	{
		scanf("%d",&n);
	    int maxsum=-INF,sum=0,temp=1;
	    int first,last;
	    for(int i=0;i<n;i++)
	    {
	    	scanf("%d",&a);
	    	sum+=a;
	    	if(sum>maxsum)
	    	{
	    		maxsum=sum;
	    		first=temp;
	    		last=i+1;
			}
	    	if(sum<0)
			{
			    sum=0;
				temp=i+2;	
			}   
		}
		printf("Case %d:\n",j);
		if(j==t) printf("%d %d %d\n",maxsum,first,last);
		else printf("%d %d %d\n\n",maxsum,first,last);
	}
	return 0;
}


























标签:HDU,sequence,Max,num,max,序列,1003,maxsum,dp
From: https://blog.51cto.com/u_14235050/6318632

相关文章

  • hdu-2680-Choose the best route(dijkstra)
    ChoosethebestrouteTimeLimit:2000/1000MS(Java/Others)    MemoryLimit:32768/32768K(Java/Others)TotalSubmission(s):10470    AcceptedSubmission(s):3367ProblemDescriptionOneday,Kikiwantstovisitoneofherfriends.Assheis......
  • hdu-1869-六度分离(dijkstra)
    六度分离TimeLimit:5000/1000MS(Java/Others)    MemoryLimit:32768/32768K(Java/Others)TotalSubmission(s):5935    AcceptedSubmission(s):2395ProblemDescription1967年,美国著名的社会学家斯坦利·米尔格兰姆提出了一个名为“小世界现象(small......
  • min-max容斥
    min-max容斥command_block-Min-Max容斥小记经常与FWT等知识搭配食用。min-max容斥证明的思想是贡献打包计算。\[\max(S)=\sum\limits_{T\subseteqS,T\neq\emptyset}(-1)^{|T|+1}\min(T)\\\min(S)=\sum\limits_{T\subseteqS,T\neq\emptyset}(-1)^{......
  • hdu:gcd(欧拉函数)
    ProblemDescriptionThegreatestcommondivisorGCD(a,b)oftwopositiveintegersaandb,sometimeswritten(a,b),isthelargestdivisorcommontoaandb,Forexample,(1,2)=1,(12,18)=6.(a,b)canbeeasilyfoundbytheEuclideanalgorithm.NowCarpiscon......
  • Row size too large. The maximum row size for the used table type, not counting B
    问题描述新建表或者修改表varchar字段长度的时候,出现这个错误Rowsizetoolarge.Themaximumrowsizefortheusedtabletype,notcountingBLOBs,is65535.Thisincludesstorageoverhead,checkthemanual.YouhavetochangesomecolumnstoTEXTorBLOBs......
  • 150kW高速永磁电机Simplorer+maxwell双闭环联合仿真 转速
    150kW高速永磁电机Simplorer+maxwell双闭环联合仿真转速与电流双闭环效果较好,资料为联合仿真的工程文件以及性能图片,学习价值非常高,值得拥有ID:946999662468374130......
  • 四相开关磁阻电机Maxwell+Simplorer联合仿真性能及其波形
    四相开关磁阻电机Maxwell+Simplorer联合仿真性能及其波形ID:99999662109233088......
  • CF269D - Maximum Waterfall
    比较迷糊,比较乱搞。我们考虑从上往下进行\(dp\),\(dp_i\)表示从顶上水槽\(i\)最多的流量。然后我们发现,每个高度,能用来进行转移的区间一定没有被完全覆盖。也就是,只有在遮挡关系中被覆盖的区间可能被用来转移。同时,每个区间还是有要求的,比如\([1,3]\)的\([2,3]\)部分后来......
  • hdu:LCIS(线段树+区间合并)
    ProblemDescriptionGivennintegers.Youhavetwooperations:UAB:replacetheAthnumberbyB.(indexcountingfrom0)QAB:outputthelengthofthelongestconsecutiveincreasingsubsequence(LCIS)in[a,b].InputTinthefirstline,indicatingt......
  • hdu:这是真正的水题(RMQ)
    ProblemDescription在缺水的地方,水是非常有限的资源,所以人们常常为争夺最大的水源而战。给定一系列水源,用a1,a2,a3,…,an代表水源的大小。给定一组查询,每个查询包含2整数L和R,请找出L和R之间最大的水源。Input输入数据首先给定一个整数T(T≤10)表示测试用例的数量。......