Interesting Sum - 题解【思维】

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 [al,al+1,,ar] of this array, meaning you can choose any two integers 1lrn, where rl+1<n. We define the beauty of a given subsegment as the value of the following expression:

max(a1,a2,,al1,ar+1,ar+2,,an)min(a1,a2,,al1,ar+1,ar+2,,an)+max(al,,ar)min(al,,ar).

Please find the maximum beauty among all proper subsegments.

Input
The first line contains one integer t(1t1000)— 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(4n105) — the length of the array.

The second line of each test case contains n integers a1,a2,,an(1ai109) — the elements of the given array.

It is guaranteed that the sum of n over all test cases does not exceed 105.

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+Mbmamb。我们发现,题目限制了序列最少含有4个元素,因此令Ma,Mb,ma,mb指代四个不同的数,这四个数在序列中的本质不同的分布情况如下:(Ma,Mb用+代替,ma,mb用-代替)

++
++

因此,我们总能选出一个子序列,这个序列的两个端点是+和-所在的位置,这样就能构造出最优情况了。所以,Ma+Mbmamb就是答案。

代码

/*
 * @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;
}

/*
          _           _    _            _
    /\   | |         | |  | |          (_)
   /  \  | | _____  _| |__| | ___  _ __ _ _ __   __ _
  / /\ \ | |/ _ \ \/ /  __  |/ _ \| '__| | '_ \ / _` |
 / ____ \| |  __/>  <| |  | | (_) | |  | | | | | (_| |
/_/    \_\_|\___/_/\_\_|  |_|\___/|_|  |_|_| |_|\__, |
                                                 __/ |
                                                |___/
*/
posted @   AlexHoring  阅读(149)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 分享一个免费、快速、无限量使用的满血 DeepSeek R1 模型,支持深度思考和联网搜索!
· 使用C#创建一个MCP客户端
· ollama系列1:轻松3步本地部署deepseek,普通电脑可用
· 基于 Docker 搭建 FRP 内网穿透开源项目(很简单哒)
· 按钮权限的设计及实现
点击右上角即可分享
微信分享提示