1247. 后缀表达式

题目链接

1247. 后缀表达式

给定 \(N\) 个加号、\(M\) 个减号以及 \(N+M+1\) 个整数 $A_1,A_2,⋅⋅⋅,A_{N+M+1},小明想知道在所有由这 \(N\) 个加号、\(M\) 个减号以及 \(N+M+1\) 个整数凑出的合法的后缀表达式中,结果最大的是哪一个?

请你输出这个最大的结果。

例如使用 \(123+−\),则 “23+1−” 这个后缀表达式结果是 \(4\),是最大的。

输入格式

第一行包含两个整数 \(N\)\(M\)

第二行包含 \(N+M+1\) 个整数 \(A_1,A_2,⋅⋅⋅,A_{N+M+1}\)

输出格式

输出一个整数,代表答案。

数据范围

\(0≤N,M≤10^5,\)
\(−10^9≤A_i≤10^9\)

输入样例:

1 1
1 2 3

输出样例:

4

解题思路

贪心

后缀表达式相当于可以对中缀表达式任意加上括号,因此可以发现:最终负号数量的范围为 \(1\sim n+m\),则可以考虑这样一个贪心策略:至少一个负号,则用在最小值上面,由于第一个数前面没有加号或者减号,取最大数即可

  • 时间复杂度:\(O(n+m)\)

代码

// Problem: 后缀表达式
// Contest: AcWing
// URL: https://www.acwing.com/problem/content/1249/
// Memory Limit: 64 MB
// Time Limit: 1000 ms
// 
// Powered by CP Editor (https://cpeditor.org)

// %%%Skyqwq
#include <bits/stdc++.h>
 
//#define int long long
#define help {cin.tie(NULL); cout.tie(NULL);}
#define pb push_back
#define fi first
#define se second
#define mkp make_pair
using namespace std;
 
typedef long long LL;
typedef pair<int, int> PII;
typedef pair<LL, LL> PLL;
 
template <typename T> bool chkMax(T &x, T y) { return (y > x) ? x = y, 1 : 0; }
template <typename T> bool chkMin(T &x, T y) { return (y < x) ? x = y, 1 : 0; }
 
template <typename T> void inline read(T &x) {
    int f = 1; x = 0; char s = getchar();
    while (s < '0' || s > '9') { if (s == '-') f = -1; s = getchar(); }
    while (s <= '9' && s >= '0') x = x * 10 + (s ^ 48), s = getchar();
    x *= f;
}

int n,m,a[200005];
LL res=0;
int main()
{
    cin>>n>>m;
    for(int i=1;i<=n+m+1;i++)
    {
    	cin>>a[i];
    	res+=a[i];
    }  
    if(m)
    {
    	res=0;
    	sort(a+1,a+n+m+2);
    	res+=-a[1]+a[n+m+1];
    	for(int i=2;i<n+m+1;i++)
    		res+=abs(a[i]);
    }
    cout<<res;
    return 0;
}
posted @ 2022-02-23 09:54  zyy2001  阅读(49)  评论(0编辑  收藏  举报