hdu 1003

The purpose of the question is to find the sum of the largest subsequence in the given sequence.
The idea is: maxsum represents the largest subsequence in the sequence a[0] to a[i], maxsum= max(max[i-1]+a[i], a[i])
There will be a negative input here, so Pay attention to the determination of the start and end positions. The place where maxsum is updated is not necessarily the place where the subsequence is the largest and where it starts, such as -1, -2, -3, and maxsum will be updated to -2, -3 every time down, but the result It is -1 1 1, which means that the position is updated only when the maximum value is determined.
Reference article: https://blog.csdn.net/xcszbdnl/article/details/7832932


#include<cstdio>
using namespace std;
int main(){
    int n,a[100010],maxsum,side,start,end,maxsum_side,ans,num;
    scanf("%d",&n);
    for(int j=0;j<n;j++){
        scanf("%d",&num);
        for(int i=0;i<num;i++){
            scanf("%d",&a[i]);
        }
        side=start=end=0;
        maxsum=ans=a[0];
        for(int i=1;i<num;i++){
            if(maxsum+a[i]<a[i]){
                 maxsum=a[i];
                 side=i;
            }
            else
                maxsum+=a[i];
            if(maxsum>ans){
                ans=maxsum;
                start=side;
                end=i;
            }
        }
        printf("Case %d:\n%d %d %d\n",j+1,ans,start+1,end+1);
        if(j!=n-1)
            printf("\n");
    }
    return 0;
}

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=324793166&siteId=291194637