杭电--1003 DP问题 max sum

题目地址:http://acm.hdu.edu.cn/showproblem.php?pid=1003

DP经典问题,求局部最大和给你一个数组,在其中取任意连续多个,使其和要最大

#include <iostream>
#include <vector>

using namespace std;

int main()
{
    int step = 1;
    int max;


    int n;
    cin >> n;
    while(n--)
    {
        max = -1001;
        int start, end;
        int k = 0;
        int num;
        int sum = 0;
        cin >> num;
        vector<int> data(num);
        for(int i=0; i<num; i++)
        {
            cin >> data[i];
        }
        for(int i=0; i<num; i++)
        {
            sum = sum + data[i];
            if(sum > max)
            {
                max = sum;
                start = k + 1;
                end = i + 1;
            }
            if(sum < 0)
            {
                sum = 0;
                k = i + 1;
            }
        }

        if(step != 1)
            cout << endl;
        cout << "Case " << step << ":" << endl;
        cout << max << " " << start << " " << end << endl;
        step++;
    }
    return 0;
}

/*
3
5 6 -1 5 4 -7
7 0 6 -1 1 -6 7 -5
5 -3 -2 -1 -2 -3


Case 1:
14 1 4

Case 2:
7 1 6

Case 3:
-1 3 3
*/



你可能感兴趣的:(杭电--1003 DP问题 max sum)