洛谷传送门
Codeforces传送门
题目描述
There are n 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 eats a slime with a value y y , the eaten slime disappears, and the value of the remaining slime changes to .
The slimes will eat each other until there is only one slime left.
Find the maximum possible value of the last slime.
输入输出格式
输入格式:
The first line of the input contains an integer n n ( ) denoting the number of slimes.
The next line contains n n integers ( −109≤ai≤109 − 10 9 ≤ a i ≤ 10 9 ), where ai a i is the value of i i -th slime.
输出格式:
Print an only integer — the maximum possible value of the last slime.
输入输出样例
输入样例#1:
4
2 1 2 1
输出样例#1:
4
输入样例#2:
5
0 -1 -1 -1 -1
输出样例#2:
4
说明
In the first example, a possible way of getting the last slime with value is:
- Second slime eats the third slime, the row now contains slimes 2,−1,1 2 , − 1 , 1
- Second slime eats the third slime, the row now contains slimes 2,−2 2 , − 2
- First slime eats the second slime, the row now contains 4 4
In the second example, the first slime can keep eating slimes to its right to end up with a value of .
题目大意
有 n n 个史莱姆,每个史莱姆有一个值 史莱姆 i i 可以吞掉其旁边的史莱姆, 生成新的一个史莱姆, 其权值为 ai−aj a i − a j , 求最后剩下的一个史莱姆的值最大是多少。
解题分析
我们要使得最后的一个史莱姆尽量大, 有两种方式可以将 ai a i 尽可能利用。
一种是用正权值的史莱姆吞掉所有负权值的, 这样最后的值就是 ∑abs(ai) ∑ a b s ( a i ) 。
一种是用负权值的史莱姆吞掉所有正权值的, 最后用一个正权值的将它吞掉。
所以有正有负的情况下最终结果都是 ∑abs(ai) ∑ a b s ( a i ) , 那么在只有负数、正数的情况下, 我们牺牲绝对值最小的一个数得到符号相反的一个数即可。 这时权值为 ∑abs(ai)−2×min abs(ai) ∑ a b s ( a i ) − 2 × m i n a b s ( a i ) 。
特判 n=1 n = 1 的情况。
代码如下:
#include <cstdio>
#include <cmath>
#include <algorithm>
#include <cctype>
#include <cstring>
#include <cstdlib>
#include <limits.h>
#define R register
#define IN inline
#define W while
#define gc getchar()
#define MX 500050
bool neg;
template <class T>
IN void in(T &x)
{
x = 0; R char c = gc;
for (; !isdigit(c); c = gc)
if(c == '-') neg = true;
for (; isdigit(c); c = gc)
x = (x << 1) + (x << 3) + c - 48;
if(neg) neg = false, x = -x;
}
int poscnt, negcnt;
long long dat[MX], mxneg = -INT_MAX, mnpos = INT_MAX;
long long ans;
int main(void)
{
int n;
scanf("%d", &n);
for (R int i = 1; i <= n; ++i)
{
in(dat[i]);
if(dat[i] >= 0) poscnt++;
else negcnt++;
}
if(n == 1) return printf("%I64d", dat[1]), 0;
if(poscnt)
{
if(negcnt)
{
for (R int i = 1; i <= n; ++i) ans += std::abs(dat[i]);
printf("%I64d", ans); return 0;
}
else
{
for (R int i = 1; i <= n; ++i)
{
ans += dat[i];
mnpos = std::min(mnpos, dat[i]);
}
printf("%I64d", ans - 2 * mnpos);
}
}
else
{
for (R int i = 1; i <= n; ++i)
{
ans += -dat[i];
mxneg = std::max(mxneg, dat[i]);
}
printf("%I64d", ans + 2 * mxneg);
}
}
//submitted by luogu