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 integers. You can choose any proper subsegment of this array, meaning you can choose any two integers , where . We define the beauty of a given subsegment as the value of the following expression:
.
Please find the maximum beauty among all proper subsegments.
Input
The first line contains one integer — the number of test cases. Then follow the descriptions of each test case.The first line of each test case contains a single integer — the length of the array.
The second line of each test case contains integers — the elements of the given array.
It is guaranteed that the sum of over all test cases does not exceed .
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
大意
给定一个序列,要求取出序列中连续的一段(不能全取),定义一个数字集合的“有趣度”为这个集合元素的最大值减去最小值(也就是极差),定义一个序列的“美丽值”为取出序列的有趣度与未被取走部分的有趣度之和。求该序列的最大美丽值。
题解
要让极差之和最大,就要让选出的最大的数尽可能大,最小的数尽可能小。我们考虑序列中最大的元素、第二大的元素,以及最小的元素、第二小的元素,即为。理论上最优的情况是。我们发现,题目限制了序列最少含有4个元素,因此令指代四个不同的数,这四个数在序列中的本质不同的分布情况如下:(用+代替,用-代替)
因此,我们总能选出一个子序列,这个序列的两个端点是+和-所在的位置,这样就能构造出最优情况了。所以,就是答案。
代码
/*
* @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;
}
/*
_ _ _ _
/\ | | | | | | (_)
/ \ | | _____ _| |__| | ___ _ __ _ _ __ __ _
/ /\ \ | |/ _ \ \/ / __ |/ _ \| '__| | '_ \ / _` |
/ ____ \| | __/> <| | | | (_) | | | | | | | (_| |
/_/ \_\_|\___/_/\_\_| |_|\___/|_| |_|_| |_|\__, |
__/ |
|___/
*/
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 分享一个免费、快速、无限量使用的满血 DeepSeek R1 模型,支持深度思考和联网搜索!
· 使用C#创建一个MCP客户端
· ollama系列1:轻松3步本地部署deepseek,普通电脑可用
· 基于 Docker 搭建 FRP 内网穿透开源项目(很简单哒)
· 按钮权限的设计及实现