题面
Given an array . In one operation, you can choose a pair of indices such that , , and remove the element at index from the array. After that, the size of the array will decrease by , and the relative order of the elements will not change.
Determine the maximum number of operations that can be performed on the array if they are applied optimally.
Input
Each test contains multiple test cases. The first line contains the number of test cases (). The description of the test cases follows.
The first line of each test case contains an integer () — the size of the initial array.
The second line of each test case contains natural numbers ().
Output
For each test case, output the maximum number of operations that you can perform on the given array.
思路
操作只会删除右端点 的元素,数组相对顺序保持不变,因此每个位置是否可删只取决于它左侧是否出现过更大的值
对位置 而言,若存在 使 ,则可选择这对 直接删除
反之,若 ,则左侧不存在更大值,后续只会删掉一些元素但不会凭空产生更大值,因此 永远不可删
因此答案等于满足 的下标个数
实现时维护前缀最大值 ,从左到右扫描,若 则计入答案,否则更新
代码
#include <bits/stdc++.h>
using namespace std;
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 = 0; int mx = a[0]; for (int i = 1; i < n; i ++) { if (mx > a[i]) ans++; else mx = a[i]; }
cout << ans << endl; }}