这个肺雾赛时当成逆序对调了 20min。
题目翻译:
给定一个 的排列 ,并保证对于所有的 ,。求 中所有区间的最长下降子序列长度之和。
首先考虑整个排列的最长下降子序列怎么求。
有一个很显然的贪心:对于所有 ,当 时,子序列中两个都选;否则放弃之前的 ,选择 。
证明:
- 当 时,,所以需要考虑的只是 与 之间选哪个的关系, 必选;
- 当 时,,又回到了上面那个情况,显然放弃 选择 更优。
所以最长下降子序列长度就是所有满足 且 的 的数量加上 。
显然这个结论可以拓展到每个区间。现在的问题是如何计算所有区间的最长下降子序列长度之和。
考虑改变计算方式。我们可以计算每个满足条件的数对能够在几个区间内出现,换句话说也就是对于每个满足条件的 ,存在多少个数对 满足 且 。显然答案是 。
因为最长下降子序列长度还得多 ,所以把所有的加起来再加上总区间数即 就是最终答案了。
#include <iostream>
#include <cstdio>
#include <vector>
#define int long long
using namespace std;
int a[500005];
int n, ct;
void solve(){
ios::sync_with_stdio(0);
cin.tie(0), cout.tie(0);
cin >> n;
for(int i = 1; i <= n; i++) cin >> a[i];
int ans = 0;
for(int i = 1; i < n; i++){
if(a[i] > a[i + 1]) ans += i * (n - i);//计算每个符合条件的数对出现在的区间数量
}
cout << ans + n * (n + 1) / 2 << '\n';//将答案加上区间个数
}
signed main(){
ios::sync_with_stdio(0);
cin.tie(0), cout.tie(0);
int t;
cin >> t;
while(t--) solve();
return 0;
}
时间复杂度 。