当前位置: 首页 > 工具软件 > slime > 使用案例 >

1038D. Slime(思维)

咸亦
2023-12-01

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

Copy

4
2 1 2 1

Output

Copy

4

Input

Copy

5
0 -1 -1 -1 -1

Output

Copy

4

Note

In the first example, a possible way of getting the last slime with value 4

is:

  • Second slime eats the third slime, the row now contains slimes 2,−1,1
  •  
  • Second slime eats the third slime, the row now contains slimes 2,−2
  •  
  • First slime eats the second slime, the row now contains 4
  •  

In the second example, the first slime can keep eating slimes to its right to end up with a value of 4

.题意:

题意是有n个史莱姆,每一个史莱姆都可以吃掉相邻的史莱姆,使得自己的值改变,当x吃掉y的时候,x的值变为x-y,问最后所剩下的史莱姆最大是多少。

思路:

  三种情况,第一种是所有数都是正数,对于这种情况我们要找一个最小值去减去一个数来获得一个负数,然后用这个负数去减别的正数从而获得更小的负数,最后再用一个正数来减去这个负数从而获得最大值,在这个过程中我们可以发现所有值最终都是被加上的,除了最小值第一次减的时候没有加上以外还少算了一次最小值,所以最终ans就是所有数的和减去2*Min,解释的不太好理解,可以写一下这个过程想想,同理当所有数都是负数的时候就是所有数的绝对值的和减去2*Max,当既有正数又有负数的时候就是输出所有元素的绝对值的和,然后就是对于n等于1和2的情况特判一下就好了。

#include<cstdio>
#include<cstring>
#include<cmath>
#include<algorithm>
#define Inf 0x7f7f7f7f
using namespace std;
typedef long long LL;
const int N = 500005;
LL arr[N];
int n;
int main(){
	scanf("%d",&n);
	LL mint=Inf,maxt=-Inf;
	LL ans=0;
	for(int i=0;i<n;i++){
		scanf("%lld",&arr[i]);
		ans+=abs(arr[i]);
		mint=min(mint,arr[i]);
		maxt=max(maxt,arr[i]);	
	}
	if(n==1) printf("%lld\n",arr[0]);
	else if(n==2)
		printf("%lld\n",max(arr[0]-arr[1],arr[1]-arr[0]));
	else{
		if(mint>0) ans-=2*mint;
		else if(maxt<0) ans-=2*abs(maxt);
		printf("%lld\n",ans);
	}
	return 0;
}

 

 类似资料: