HDOJ 1003 Max Sum

~~~题目链接~~~


思路:前几个数的连续和加上当前这个数, 如果比当前这个数小就从当前这个位开锁重新记区间,否则加入当前区间,注意有负数, 不能用连续的几个数和小于0做结束判断 


code:

#include <iostream>
#include <algorithm>
using namespace std;
int main()
{
    int i = 0, j = 0, t = 0, x = 0, y = 0, cnt = 0, ans = -0x7fffffff, ansx = 0, ansy = 0;
    int num[100002];
    cin>>t;
    while(t--)
    {
        ans = -0x7fffffff, x = 1;
        int n = 0;
        cin>>n;
        for(i = 0; i<n; i++)
            cin>>num[i];
        int sum = 0, max = -0x7fffffff;
        for(i = 0; i<n; i++)
        {
            sum += num[i];
            if(sum<num[i])
            {
                x = i+1;
                y = i+1;
                sum = num[i];
            }
            if(max<sum)
            {
                max = sum;
                y = i+1;
            }
            if(ans<max)
            {
                ans = max;
                ansx = x;
                ansy = y;
            }
        }
        cout<<"Case "<<++cnt<<":"<<endl;
        cout<<ans<<" "<<ansx<<" "<<ansy<<endl;
        if(t != 0)
            cout<<endl;
    }
    return 0;
}


你可能感兴趣的:(HDOJ 1003 Max Sum)