nyoj蚂蚁的难题

蚂蚁的难题(二)

时间限制: 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;
		}
	}
}

点击打开链接
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值