1. 程式人生 > >Codeforces Round #508 (Div. 2) D. Slime【思維】

Codeforces Round #508 (Div. 2) D. Slime【思維】

D. Slime

time limit per test

2 seconds

memory limit per test

256 megabytes

input

standard input

output

standard output

There are nn 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 xx eats a slime with a value yy, the eaten slime disappears, and the value of the remaining slime changes to x−yx−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 nn (1≤n≤5000001≤n≤500000) denoting the number of slimes.

The next line contains nn integers aiai (−109≤ai≤109−109≤ai≤109), where aiai is the value of ii-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 44 is:

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

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

題意: 給你一行整數數,然後每一個數x都可以吃掉它與他相鄰的數y,被吃掉的數y會消失,之前的那個數x則會變成x-y,這行數最後只能剩下一個數,問這個數最後最大是多少?

題解:如果給出的n個數有正有負,則結果為所有數的絕對值;如果給出的n個數有0存在,那麼結果仍是所有數的絕對值;如果全為負數或全為正數,則只需要選擇兩個對整體結果影響最小的數就可以了。還要特別注意一下n==1的情況。

如果x>0,y<0,那麼最佳值為|x|+|y|;如果x>0,y>0,那麼最佳值為x-y或y-x。由此可知異號之間的數在進行計算時,不會有值上的損耗。一個數與0之間的計算也不會有值上的損耗;只有同號之間才會有損耗,同號之間計算出一個負數,與之相反號的數,這時,整個數列又變成了異號純在的數列,也就是值確定了,也就說只需選出最佳的兩個數變換即可。

程式碼如下:

#include<cstdio>
#include<iostream>
#include<algorithm>
#include<cmath>
using namespace std;
typedef long long ll;
ll a[500005];

int main()
{
	ll n;
	scanf("%lld",&n);
	ll sum=0;
	int flag0=0,flag1=0,flag2=0;
	for(ll i=0;i<n;i++){
		scanf("%lld",&a[i]);
		sum+=abs(a[i]);
		if(a[i]==0){
			flag0=1;
		}else if(a[i]>0){
			flag1=1;
		}else{
			flag2=1;
		}
	}
	if(n==1){
		printf("%lld\n",a[0]);
	}else if(flag0||flag1&&flag2){
		printf("%lld\n",sum);
	}else{
	
		ll mi=min(abs(a[0])-abs(a[1]),abs(a[1])-abs(a[0]));
		ll mik=sum-abs(a[0])-abs(a[1])-mi;
		
		for(ll i=2;i<n;i++){
			
			if(sum-min(abs(a[i])-abs(a[i-1]),abs(a[i-1])-abs(a[i]))-abs(a[i])-abs(a[i-1])>mik){
				
				mik=sum-min(abs(a[i])-abs(a[i-1]),abs(a[i-1])-abs(a[i]))-abs(a[i])-abs(a[i-1]);
			}
		}
		
		printf("%lld\n",mik);
		
	}
	
	
	
	return 0;
 }