练习cf1726A. Mainak and Array
题目如下
https://codeforces.com/problemset/problem/1726/A
A. Mainak and Array
time limit per test1 second
memory limit per test256 megabytes
Mainak has an array 𝑎1,𝑎2,…,𝑎𝑛 of 𝑛 positive integers. He will do the following operation to this array exactly once:
Pick a subsegment of this array and cyclically rotate it by any amount.
Formally, he can do the following exactly once:
Pick two integers 𝑙 and 𝑟, such that 1≤𝑙≤𝑟≤𝑛, and any positive integer 𝑘.
Repeat this 𝑘 times: set 𝑎𝑙=𝑎𝑙+1,𝑎𝑙+1=𝑎𝑙+2,…,𝑎𝑟−1=𝑎𝑟,𝑎𝑟=𝑎𝑙 (all changes happen at the same time).
Mainak wants to maximize the value of (𝑎𝑛−𝑎1) after exactly one such operation. Determine the maximum value of (𝑎𝑛−𝑎1) that he can obtain.
Input
Each test contains multiple test cases. The first line contains a single integer 𝑡 (1≤𝑡≤50) — the number of test cases. Description of the test cases follows.
The first line of each test case contains a single integer 𝑛 (1≤𝑛≤2000).
The second line of each test case contains 𝑛 integers 𝑎1,𝑎2,…,𝑎𝑛 (1≤𝑎𝑖≤999).
It is guaranteed that the sum of 𝑛 over all test cases does not exceed 2000.
Output
For each test case, output a single integer — the maximum value of (𝑎𝑛−𝑎1) that Mainak can obtain by doing the operation exactly once.
题目大意
现有数组,可以通过选择中间某一段从r到l,进行任意次𝑎𝑙=𝑎𝑙+1,𝑎𝑙+1=𝑎𝑙+2,…,𝑎𝑟−1=𝑎𝑟,𝑎𝑟=𝑎𝑙 操作,使得𝑎𝑛−𝑎1最大,输出最大的值。
题目分析
因为题目只允许一次子段循环移动,做不到完全自由的重排,所以不能直接用最大数减去最小数;那么我们可以通过枚举所有可能的r到l的子段,计算每次a[n] - a[1]的值,找出最大可能值;
点击查看代码
#include <stdio.h>
#include <vector>
#include <algorithm>
using namespace std;
int main(){
int t;
scanf("%d", &t);
while(t--){
int n;
scanf("%d", &n);
vector<int> a(n);
for(int i = 0; i < n; i++){
scanf("%d", &a[i]);
}
int ans = a[n - 1] - a[0];
for(int i = 0; i < n - 1; i++){
ans = max(ans, a[i] - a[0]);
}
for(int i = 1; i < n; i++){
ans = max(ans, a[n - 1] - a[i]);
}
for(int i = 1; i < n; i++){
ans = max(ans, a[i - 1] - a[i]);
}
printf("%d\n", ans);
}
return 0;
}

浙公网安备 33010602011771号