练习cf1832C. Contrast Value
题目如下
C. Contrast Value
time limit per test2 seconds
memory limit per test256 megabytes
For an array of integers [𝑎1,𝑎2,…,𝑎𝑛], let's call the value |𝑎1−𝑎2|+|𝑎2−𝑎3|+⋯+|𝑎𝑛−1−𝑎𝑛| the contrast of the array. Note that the contrast of an array of size 1 is equal to 0.
You are given an array of integers 𝑎. Your task is to build an array of 𝑏 in such a way that all the following conditions are met:
𝑏 is not empty, i.e there is at least one element;
𝑏 is a subsequence of 𝑎, i.e 𝑏 can be produced by deleting some elements from 𝑎 (maybe zero);
the contrast of 𝑏 is equal to the contrast of 𝑎.
What is the minimum possible size of the array 𝑏?
Input
The first line contains a single integer 𝑡 (1≤𝑡≤104) — the number of test cases.
The first line of each test case contains a single integer 𝑛 (1≤𝑛≤3⋅105) — the size of the array 𝑎.
The second line contains 𝑛 integers 𝑎1,𝑎2,⋅,𝑎𝑛 (0≤𝑎𝑖≤109) — elements of the array itself.
The sum of 𝑛 over all test cases doesn't exceed 3⋅105.
Output
For each test case, print a single integer — the minimum possible size of the array 𝑏.
题目大意
根据题意,对比值是整个数组每两个相邻元素的差的绝对值之和,如 |𝑎1−𝑎2|+|𝑎2−𝑎3|+⋯+|𝑎𝑛−1−𝑎𝑛|所示。
现在探索是否可以通过删除原数组中的一些元素但不改变原数组元素的顺序使得新数组的对比值与原数组的对比值一致,输出符合要求的数组的最小长度。
题目分析
要求对比值相同,只与数组中元素的趋势有关,意思是其中某子段呈现上升或下降趋势,那么这一段的对比值只与子段的首位和末尾有关,那么除子段的首和末尾其他都不能影响本段的对比值;同理,连续的值相同的元素同样不能改变对比值。
对于上述不能改变整个数组对比值的元素,为了尽量减小长度,都可以进行删除操作。
点击查看代码
#include <iostream>
#include <vector>
using namespace std;
int main(){
int t;
cin >> t;
while(t--){
int n;
cin >> n;
vector<long long> a(n), b;
for(int i = 0; i < n; i++){
cin >> a[i];
}
b.push_back(a[0]);
for(int i = 1; i < n; i++){
if(a[i] != a[i-1]){
b.push_back(a[i]); //去连续重复元素
}
}
vector<long long> c;
int m = b.size();
if(m == 1){
c.push_back(b[0]);
}else{
c.push_back(b[0]);
for(int i = 1; i < m - 1; i++){
if((b[i] > b[i - 1] && b[i] > b[i + 1]) ||
(b[i] < b[i - 1] && b[i] < b[i + 1])){ //判断拐点
c.push_back(b[i]);
}
}
c.push_back(b[m - 1]);
}
cout << c.size() << endl;
}
return 0;
}

浙公网安备 33010602011771号