HDU1003 dp 动态规划解析

此博客介绍了一个算法,用于查找输入序列中具有最大和的连续子序列,并输出其开始和结束位置。该算法通过迭代计算每个元素的前缀和来确定最大子序列。

 

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.


#include<iostream>
using namespace std;
int main()
{
 int N;
 cin>>N;
 int i,count=1;
 while(N--)
 {
  int n;
  int now,before,sum,x,y,z;
  cin>>n;
  for(i=1;i<=n;i++)
  {
   cin>>now;
   if(i==1)
   {
    sum=before=now;//sum保存最大和,before保存当前的和 ,x表示before的起始位置,y,z表示sum的始末位置
    x=y=z=i;
   }
   else
   {
    if(now+before>now)
     before=before+now;
    else
    {
     befor=now;
     x=i;//预存位置要重置
    }
   }
   if(before>sum)
   {
    sum=before;
    y=x;
    z=i;
   }

  }
  cout<<"Case "<<count++<<":"<<endl<<sum<<" "<<y<<" "<<z<<endl;
  if(N>=1)
   cout<<endl;
 }
 return 0;
}

转载于:https://www.cnblogs.com/yfz1552800131/p/5329226.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值