CF1038D Slime

洛谷 CF1038D Slime

题目传送门

题意翻译

题目大意:

有nn只史莱姆qwq,每只史莱姆有一个分数,每次一只史莱姆可以吞掉左边的或者右边的史莱姆(要是有的话),然后ta的分数会减去被吞的史莱姆的分数,问最后剩下的史莱姆分数最大为多少

输入格式:

第一行一个整数nn

第二行nn个整数,表示史莱姆的分数

输出格式:

一个整数,即最大分数

### 题目大意:
有$n$只史莱姆qwq,每只史莱姆有一个分数,每次一只史莱姆可以吞掉左边的或者右边的史莱姆(要是有的话),然后ta的分数会减去被吞的史莱姆的分数,问最后剩下的史莱姆分数最大为多少

### 输入格式:
第一行一个整数$n$

第二行$n$个整数,表示史莱姆的分数

### 输出格式:
一个整数,即最大分数

题目描述

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 - yxy .

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 nn ( 1 \le n \le 500,0001≤n≤500000 ) denoting the number of slimes.

The next line contains nn integers a_i*a**i* ( -10^9 \le a_i \le 10^9−109≤ai≤109 ), where a_iai is the value of ii -th slime.

输出格式

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

输入输出样例

输入 #1复制

输出 #1复制

输入 #2复制

输出 #2复制

说明/提示

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 .

题目大意:

一个数列,相邻的数可以相减,问减到最后一个数后最后的那个数可能的最大值是多少。

题解:

这是一道数学推导问题:

首先我们分类讨论:这题一共有三种大的情况:

全是正数,全是负数,有正数也有负数。

我们来看:

假如有正有负,那么我们可以用负数减去正数,让其越减越小,但绝对值越大,最后用正数减去,就能得到最大的值,这样我们虽然一直在减来减去,但是绝对值一直没有变,最后输出的答案也是“没有损耗”的,所以,假如有正有负,最后的答案就应该是所有数绝对值的和

假如全是正数,那么我们通过刚才的推理考虑,一定要产生负数,最后用正数减去负数得到一个更大的正数,所以我们尽可能地用小的减去大的。同理,如果全是负的,就用大的减去小的。所以,假如全正全负,最后的答案就应该是所有数绝对值的和减去所有数中绝对值最小的数的二倍

代码:(注意特判n=1的情况)

#include<cstdio>
#include<cmath>
#include<algorithm>
#define ll long long
using namespace std;
int n;
int pos,neg;
ll sum,minn=1e9;
int main()
{
    scanf("%d",&n);
    if(n==1)
    {
        ll a;
        scanf("%lld",&a);
        printf("%lld",a);
        return 0;
    }
    for(int i=1;i<=n;i++)
    {
        ll a;
        scanf("%lld",&a);
        if(a>0)
            pos++;
        if(a<0)
            neg++;
        sum+=abs(a);
        minn=min(minn,abs(a));
    }
    if(pos>0 && neg>0)
        printf("%lld",sum);
    else
        printf("%lld",sum-minn*2);
    return 0;
}

猜你喜欢

转载自www.cnblogs.com/fusiwei/p/11353090.html
今日推荐