Interesting Sum - 题解【思维】
前言
在vscode上配置了markdown插件,取代了之前写md的工具,本博客用来测试插件好不好用,所以选的题比较简单。但是jiangly这道题被FST了【滑稽】
题面
本题是Codeforces #815 Div.2的B题。原题链接见:B.Interesting Sum。下面搬运一下题面:
You are given an array a that contains \(n\) integers. You can choose any proper subsegment $ [a_l, a_{l + 1}, \ldots, a_r ] $ of this array, meaning you can choose any two integers \(1 \le l \le r \le n\), where \(r - l + 1 < n\). We define the beauty of a given subsegment as the value of the following expression:
\(\max(a_{1}, a_{2}, \ldots, a_{l-1}, a_{r+1}, a_{r+2}, \ldots, a_{n}) - \min(a_{1}, a_{2}, \ldots, a_{l-1}, a_{r+1}, a_{r+2}, \ldots, a_{n}) + \max(a_{l}, \ldots, a_{r}) - \min(a_{l}, \ldots, a_{r})\).
Please find the maximum beauty among all proper subsegments.
Input
The first line contains one integer $t (1 \leq t \leq 1000) $— the number of test cases. Then follow the descriptions of each test case.The first line of each test case contains a single integer \(n (4 \leq n \leq 10^5)\) — the length of the array.
The second line of each test case contains \(n\) integers \(a_1, a_2, \ldots, a_n (1 \leq a_{i} \leq 10^9)\) — the elements of the given array.
It is guaranteed that the sum of \(n\) over all test cases does not exceed \(10^5\).
Output
For each testcase print a single integer — the maximum beauty of a proper subsegment.Sample input
4 8 1 2 2 3 1 5 6 1 5 1 2 3 100 200 4 3 3 3 3 6 7 8 3 1 1 8
Sample output
9 297 0 14
大意
给定一个序列,要求取出序列中连续的一段(不能全取),定义一个数字集合的“有趣度”为这个集合元素的最大值减去最小值(也就是极差),定义一个序列的“美丽值”为取出序列的有趣度与未被取走部分的有趣度之和。求该序列的最大美丽值。
题解
要让极差之和最大,就要让选出的最大的数尽可能大,最小的数尽可能小。我们考虑序列中最大的元素、第二大的元素,以及最小的元素、第二小的元素,即为\(Ma,Mb,ma,mb\)。理论上最优的情况是\(Ma+Mb-ma-mb\)。我们发现,题目限制了序列最少含有4个元素,因此令\(Ma,Mb,ma,mb\)指代四个不同的数,这四个数在序列中的本质不同的分布情况如下:(\(Ma,Mb\)用+代替,\(ma,mb\)用-代替)
\(+ + - -\)
\(+ - + -\)
因此,我们总能选出一个子序列,这个序列的两个端点是+和-所在的位置,这样就能构造出最优情况了。所以,\(Ma+Mb-ma-mb\)就是答案。
代码
/*
* @Author: AlexHoring
* @Date: 2022-08-18 21:51:38
*/
#include <bits/stdc++.h>
#define GRP int T;cin>>T;rep(C,1,T)
#define FAST ios::sync_with_stdio(false);cin.tie(0);
#define rep(i,a,b) for(int i=a;i<=b;++i)
#define rrep(i,a,b) for(int i=a;i>=b;--i)
#define elif else if
#define mem(arr,val) memset(arr,val,sizeof(arr))
typedef long long ll;
typedef unsigned long long ull;
using namespace std;
int a[100010];
int n;
int main() {
#ifdef AlexHoring
freopen("a.in", "r", stdin);
freopen("a.out", "w", stdout);
#endif
FAST;
GRP{
cin >> n;
rep(i,1,n) {
cin >> a[i];
}
sort(a + 1,a + 1 + n);
cout << a[n] + a[n - 1] - a[1] - a[2] << endl;
}
return 0;
}
/*
_ _ _ _
/\ | | | | | | (_)
/ \ | | _____ _| |__| | ___ _ __ _ _ __ __ _
/ /\ \ | |/ _ \ \/ / __ |/ _ \| '__| | '_ \ / _` |
/ ____ \| | __/> <| | | | (_) | | | | | | | (_| |
/_/ \_\_|\___/_/\_\_| |_|\___/|_| |_|_| |_|\__, |
__/ |
|___/
*/
标签:Ma,Mb,题解,Sum,leq,Interesting,序列,ldots,define
From: https://www.cnblogs.com/AlexHoring/p/16606918.html