题目来源
2014年蓝桥杯省赛
题目链接:
https://www.lanqiao.cn/problems/222/learning//
考点
归并 、逆序对、树状数组
视频讲解
https://www.bilibili.com/video/BV1VY411J7nP
思路
这个题目我们可以很明显的和冒泡排序联系起来,我们需要知道对于第 i i i 个同学左边有多少个同学( L i L_i Li )的身高是高于他的,右边有多少个同学( R i R_i Ri )的升高是低于他的,然后我们会发现对于第 i i i 个同学实际上会进行的交换次数就是 ( L i + R i ) (L_i + R_i) (Li+Ri) ,又由于前者其实就是逆序对,后者就是顺序对,那么我们通过树状数组正着求一次逆序对数量,然后反着求一次顺序对就好啦,最后由于不高兴程度是一个从1开始的等差数列,我们通过其求和公式就能计算出啦,详情请看代码,当然关于归并排序的写法就由大家思考了哦
代码
#include<bits/stdc++.h>
using namespace std;
#define ll long long
#define mod 1000000007
#define endl "\n"
#define PII pair<int,int>
#define INF 0x3f3f3f3f
const int N = 1e6 + 10;
ll a[N],ans[N],n;
struct BIT{
ll tree[N<<2];
ll lowbit(ll x) {
return -x & x;}
void update(ll x,ll k) {
while(x < N) {
tree[x] += k;
x += lowbit(x);
}
}
ll query(ll x) {
ll ans = 0LL;
while(x){
ans += tree[x];
x -= lowbit(x);
}
return ans;
}
void clear(){
memset(tree,0,sizeof tree);
}
}bit;
int main()
{
ios::sync_with_stdio(0);cin.tie(0);cout.tie(0);
cin>>n;
for(int i = 1;i <= n; ++i) cin>>a[i],a[i]++;
for(ll i = 1;i <= n; ++i) {
bit.update(a[i],1LL);
ans[i] = i - bit.query(a[i]);
}
bit.clear();
for(ll i = n;i >= 1; --i) {
bit.update(a[i],1LL);
ans[i] += bit.query(a[i] - 1LL);
}
ll res = 0LL;
for(int i = 1;i <= n; ++i)
res += (ans[i] + 1LL) * ans[i] / 2LL;
cout<<res<<endl;
return 0;
}