题面
You are given an array of integers .
The value of an array is the sum of the maximums of each prefix of the array. More formally, the value of an array is . For example, the value of the array [] is .
You can choose two indices and and swap elements and ; this operation can be applied at most one time.
Find the maximum possible value of the array after at most one operation.
Input
The first line of the input contains a single integer () — the number of test cases.
The first line of each test case contains a single integer () — the length of the array .
The second line contains integers () — the array .
Output
For each test case, output the maximum possible value of the array after the swap has been performed.
思路
理清题目中的数组价值的含义为:
因此我们肯定需要一个函数来计算这个价值,我们将其命名为 get_v
由于题目要求的是交换任意一对索引之后的数组价值最大值,且交换操作只能执行一次,我们可以考虑暴力枚举进行
NOTE为什么可以考虑暴力枚举? 注意到 ,使得总方案数很小,所以时间复杂度可控
但是需要注意的是,在执行完调换的操作之后,需要将调换的元素进行还原,以免导致数组错乱引发的价值计算错误
代码
#include <bits/stdc++.h>
using namespace std;
int get_v(std::vector<int> a) { int result = 0; for (int i = 0; i < a.size(); i ++) { int mx = a[i]; for (int j = 0; j <= i; j ++) { if (a[j] > mx) mx = a[j]; } result += mx; } return result;}
int main() { int t; cin >> t; while (t --) { int n; cin >> n; vector<int> a(n); for (int i = 0; i < n; i ++) cin >> a[i];
int ans = get_v(a);
for (int i = 0; i < n; i ++) { for (int j = i + 1; j < n; j ++) { int tmp = a[i], ri = 0, rj = 0; a[i] = a[j]; a[j] = tmp; ans = max(ans, get_v(a)); a[i] = ri; a[j] = rj; } } cout << ans << endl; }}