循环数组求最大子段和系列------方法2
2015-03-22 17:03
239 查看
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; } |
相关文章推荐
- 循环数组求最大子段和系列-----------方法1
- 循环数组求最大子段和系列------------普通数组求组大子段和
- 51nod 1050 循环数组最大子段和 (dp)
- 动态规划--循环数组最大子段和
- 51nodLearning-dp入门之循环数组的最大子段和
- 51Nod-1050-循环数组最大子段和
- 循环数组最大子段和(DP)
- 51nod 1050 循环数组最大子段和 dp
- 1050 循环数组最大子段和
- 51 node 1050循环数组最大子段和
- 51nod 循环数组最大子段和(动态规划)
- 1050 循环数组最大子段和
- 51nod 1050 循环数组最大子段和
- 51nod 循环数组最大子段和 (dp)
- 51nod循环数组最大子段和
- 循环数组的最大子段和
- 动态规划[入门]2-循环数组最大子段和
- 动态规划-循环数组最大子段和
- 循环数组最大子段和 ~~~~暴力出奇迹
- 循环数组最大子段和