蚂蚁的难题(二)
时间限制:
1000 ms | 内存限制:
65535 KB
难度:
3
-
描述
-
下雨了,下雨了,蚂蚁搬家了。
已知有n种食材需要搬走,这些食材从1到n依次排成了一个圈。小蚂蚁对每种食材都有一个喜爱程度值Vi,当然,如果Vi小于0的时候,表示蚂蚁讨厌这种食材。因为马上就要下雨了,所以蚂蚁只能搬一次,但是能够搬走连续一段的食材。时间紧急,你快帮帮小蚂蚁吧,让它搬走的食材喜爱值和最大。
-
输入
-
有多组测试数据(以EOF结尾)。
每组数据有两行,第一行有一个n,表示有n种食材排成了一个圈。(1 <= n<= 50000)
第二行分别有n个数,代表蚂蚁对第n种食材的喜爱值Vi。(-10^9 <= Vi <= 10^9)
输出
- 输出小蚂蚁能够搬走的食材的喜爱值总和的最大。 样例输入
-
3 3 -1 2 5 -8 5 -1 3 -9
样例输出
-
5 7
-
ac代码:
-
#include<iterator> #include<fstream> #include<string> #include<set> #include<vector> #include<iostream> #include<cstring> #include<math.h> #include<algorithm> #include<stack> #include<cstdio> #include<list> #include<stdio.h> #include<stdlib.h> using namespace std; long long a[50005]; int main() { int n; while(scanf("%d",&n)!=EOF) { long long tot=0; for(int i=0;i<n;i++) { scanf("%lld",&a[i]); tot+=a[i]; } if(n==1) { cout<<a[0]<<endl; continue; } long long sum=a[0]; long long max2=a[0]; for(int i=1;i<n;i++) { if(sum<0) { sum=a[i]; } else { sum+=a[i]; } if(max2<sum) { max2=sum; } } long long min2=a[0]; long long sum2=a[0]; for(int i=1;i<n;i++) { if(sum2>0) { sum2=a[i]; } else { sum2+=a[i]; } if(sum2<min2) { min2=sum2; } } if(max2>tot-min2) { cout<<max2<<endl; } else { cout<<tot-min2<<endl; } } }
点击打开链接
-
有多组测试数据(以EOF结尾)。