循环数组求最大子段和系列-----------方法1
来源:互联网 发布:生理学软件 编辑:程序博客网 时间:2024/05/16 19:28
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.
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
For each test case print one integer describing the maximum money they can make in total.
Sample Input33 1 2 38 4 5 -1 -1 1 -1 -1 52 -1 -1Sample Output
6140
该题就是典型的求循环数组中最大子段和的问题!当然要暴力解决就可以直接写两个for循环,不过当然也肯定过不了,超时!!所以就需要想一下其他方法。在专题第一讲中我们知道了怎么求普通数组中最大子段和的问题,我们想一下是不是循环数组可以和普通数组挂钩呢??
其实循环数组中最大值也可能是普通数组中的最大值,还有可能是数组首尾相连后的部分出现最大值。那么第一种情况我们当然会解决,但是后者呢??
可以想一下为什么会出现后者这种情况。不难想到,之所以会出现后者是因为普通数组中有一段连续的和为负数,并且绝对值比较大,以至于影响到普通数组首尾相连后最大子段数发生改变。所以我们只需要把原来数组中的数全部取相反数再由普通数组方法求出最大子段数的和就是原来数组中连续负数的绝对值max2;当然一开始要求出普通数组中最大子段和max1,和总和sum。比较max1和sum+max2,就可以得到答案。
代码如下:
<span style="font-size:18px;">#include <iostream>#include <algorithm>#include <cstdio>using namespace std;#define max(a,b) ((a)>(b)?(a):(b))#define MAXN 1000005int a[MAXN];int max_sum(int a[],int n);int main(){ int n,i,t; cin>>t; while(t--) { int sum=0; cin>>n; for(i=0;i<n;i++) { cin>>a[i]; sum+=a[i]; } int max1=max_sum(a,n); for(i=0;i<n;i++) a[i]=-a[i]; int max2=max_sum(a,n); cout<<max(max1,sum+max2)<<endl; }}int max_sum(int a[],int n){ int sub_array=0; int i,sum=0; for(i=0;i<n;i++) { if(sum>=0) sum+=a[i]; else sum=a[i]; if(sub_array<sum) sub_array=sum; } return sub_array;}</span>
- 循环数组求最大子段和系列-----------方法1
- 循环数组求最大子段和系列------方法2
- 循环数组求最大子段和系列------------普通数组求组大子段和
- DP-循环数组最大子段和
- 循环数组的最大子段和
- 循环数组的最大子段和
- 1050 循环数组最大子段和
- 1050 循环数组最大子段和
- 循环数组最大子段和
- 1050 循环数组最大子段和
- 循环数组的最大子段和
- 循环数组最大子段和
- 【hpuoj】循环数组最大子段和
- 循环数组最大子段和
- 1050 循环数组最大子段和
- 循环数组最大子段和
- 循环数组最大子段和 (dp)
- 循环数组最大子段和
- ListView控件和如何向ListView控件添加数据适配器
- 为什么析构函数常常声明为虚函数
- SQL Server 优化存储过程的七种方法
- 三星NOTE3 N900 刷机
- UVA - 624 - CD (动态规划)
- 循环数组求最大子段和系列-----------方法1
- android系统自带的字体外观
- 顺序统计
- 剖析Activity
- javascript语言扩展:可迭代对象(3)
- hdu5191
- 黑马程序员——Java面向对象知识点(一)
- zendframework+composer+certificate verify failed
- PYTHON数据,赋值