题面
You are given an integer array of length .
For each index , find the maximum number of indices such that and , over all possible integer values of .
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 second line contains integers ().
It is guaranteed that the sum of over all test cases does not exceed .
Output
For each test case, output integers denoting the answer.
思路
对固定的位置 ,我们可以任选整数 ,并统计有多少个 使得 ,目标是在所有 中让这个数量最大化
核心观察是把 与 的大小关系分开考虑
当 时,比较 与 可推出成立条件等价于 ,因此这类 只有在 取在 右侧时才可能被计入
当 时,同理可推出成立条件等价于 ,因此这类 只有在 取在 左侧时才可能被计入
当 时严格不等式永远不成立,因此不影响答案
因为同一个 不可能同时满足 与 ,所以对某个固定的 来说,能被计入的 必然只来自后缀中比 大的一侧或比 小的一侧
因此答案就是两侧计数的最大值
这个上界可以通过极端取值的 直接达到
取足够大的 会让所有满足 的位置都满足 ,得到第一项
取足够小的 会让所有满足 的位置都满足 ,得到第二项
代码
#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]; }
vector<int> ans(n); for (int i = 0; i < n; i ++) { int less = 0, greater = 0; for (int j = i + 1; j < n; j ++) { if (a[j] < a[i]) less ++; else if (a[j] > a[i]) greater ++; } ans[i] = max(less, greater); }
for (int i = 0; i < n; i ++) { cout << ans[i] << " \n"[i == n - 1]; } }}