cf1038D水题

There are n slimes in a row. Each slime has an integer value (possibly negative or zero) associated with it.

Any slime can eat its adjacent slime (the closest slime to its left or to its right, assuming that this slime exists).

When a slime with a value x eats a slime with a value y, the eaten slime disappears, and the value of the remaining slime changes to x−y.

The slimes will eat each other until there is only one slime left.

Find the maximum possible value of the last slime.

Input
The first line of the input contains an integer n (1≤n≤500000) denoting the number of slimes.

The next line contains n integers ai (−109≤ai≤109), where ai is the value of i-th slime.

Output
Print an only integer — the maximum possible value of the last slime.

Examples
Input
4
2 1 2 1
Output
4
Input
5
0 -1 -1 -1 -1
Output
4
题意:有一排带有数值的史莱姆,数值可正可负。任意史莱姆都可以吃掉相邻的其他史莱姆,当一个值为x的史莱姆吃掉一个值为y的史莱姆时,被吃掉的便消失,而剩下的史莱姆的值则变为x - y。现在求一排史莱姆相互吞噬能得到最大的史莱姆数值是多少。
思路:
如果数值有正有负,就让负的去吃正的,只留一个正的,然后正的吃掉所有负的,不会有损耗,最终结果是所有史莱姆数值绝对值之和。
如果所有数值都是正的,就让最小的去吃其他史莱姆变成负的,同样留一个正的去吃掉这个负的,结果是所有数值的和减去两倍的最小值;全为负的同理全为正的。

#include<cstring>
#include<algorithm>
#include<cmath>
using namespace std;
int main ()
{
	int n;
	cin>>n;
	if(n==1)
	{
		int x;
		cin>>x;
		cout<<x<<endl;
		return 0;
	}
	long long cnt=0,sum=0;
	long long minn=1e9+10;
	long long ans=0;
	for(int i=1;i<=n;i++)
	{
		long long x;
		cin>>x;
		if(x<0)
		cnt++;
		if(x>0)
		sum++;
		ans+=abs(x);
		minn=min(minn,abs(x));
	}
	if(cnt!=0&&sum!=0)
	{
		cout<<ans<<endl;
	}
	else
	{
		ans-=minn*2;
		cout<<ans<<endl;
	}
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值