循环数组求最大子段和系列------方法2

Equator
Time Limit: 2000ms, Special Time Limit:5000ms,Memory Limit:65536KB
Total submit users: 12, Accepted users:8
Problem 13248 : No special judgement
Problem description

In a galaxy far away, the planet Equator is under attack! The evil gang Galatic Criminal People Cooperation is planning robberies in Equator’s cities. Your help is needed! In order to complete your training for becoming a lord of the dark side you should help them deciding which cities to rob. As the name says, the desert planet Equator only can be inhabited on its equator. So the gang lands there at some point and travels into some direction robbing all cities on their way until leaving the planet again.

But what is still open for them is to decide where to land, which direction to take, and when to leave. Maybe they shouldn’t even enter the planet at all? They do not consider costs for traveling or for running their ship, those are peanuts compared to the money made by robbery!

The cities differ in value: some are richer, some are poorer, some have better safety functions. So the gang assigned expected profits or losses to the cities. Help them deciding where to begin and where to end their robbery to maximize the money in total when robbing every city in between.

Input

Output

For each test case print one integer describing the maximum money they can make in total.

Sample Input
3
3 1 2 3
8 4 5 -1 -1 1 -1 -1 5
2 -1 -1
Sample Output
6
14
0

     在这里继续介绍一种新的方法,这个原理就是把数组的大小开成两倍,建一个队列,保证队列单增,队列里的值是数组前n项和,那么子段的最大和就是队尾减队首。

代码如下:

     

#include <iostream>
#include <algorithm>
#include <cstdio>
using namespace std;
#define max(a,b) ((a)>(b)?(a):(b))
#define MAXN  1000010

int max_sub_array(int b[],int n);
int a[MAXN],b[MAXN<<1],que[MAXN<<1];
int main()
{   int T;
    cin>>T;
    while(T--)
    {   int n;
        cin>>n;

        for(int i=1;i<=n;i++)
            cin>>a[i];
        b[0]=0;
        for(int i=1;i<=2*n;i++)
            if(i<=n)
                b[i]=b[i-1]+a[i];
            else
                b[i]=b[i-1]+a[i-n];

        cout<<max_sub_array(b,n)<<endl;
    }
    return 0;
}
int max_sub_array(int b[],int n)
{   int h=0,t=0;
    int ans=0;

    que[0] = ans = 0;
    for(int i = 1; i <= 2 * n; i++)
    {
        while(t >= h && b[i] < b[que[t]])
        {   ans = max(ans, b[que[t]] - b[que[h]]);
            t--;
        }
        while(t >= h && i - que[h] > n)
        {   ans = max(ans, b[que[t]] - b[que[h]]);
            h++;
        }
        que[++t] = i;
    }
    ans = max(ans, b[que[t]] - b[que[h]]);
    return ans;
}


     

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值