Asia Yokohama Regional Contest 2018 G题 What Goes Up Must Come Down(树状数组求逆序对)

https://codeforces.com/gym/102082

题意:

  给一个数组大小不超过1e5,每个数的值也是1e5以内,可以交换相邻两个数,求保证它呈现一个非递减再非递增的趋势的最小交换次数。

 
题解:
  对每个数来说,只有两种情况,要么参与非递减部分要么参与非递增部分,对于前者它要移的次数就是在它之前与他构成的逆序对数,对于后者它要移的次数就是在它之后与他构成的逆序对数,那我们取较小的加入到答案就做完了。
#define bug(x,y) cout<<"i="<<x<<": "<<y<<endl
#define IO std::ios::sync_with_stdio(0);
#include <bits/stdc++.h>
#define itor ::iterator
using namespace  std;
typedef long long ll;
typedef pair<ll,ll>P;
#define pb push_back
#define se second
#define fi first
#define rs o*2+1
#define ls o*2
const int N=1e5+5;
int n;
int c[N];
int low(int x){
    return x&(-x);
}
void add(int x,int y){
    while(x<N){   
        c[x]+=y;
        x+=low(x);
    }
}
int cal(int x){
    int res=0;
    while(x){
        res+=c[x];
        x-=low(x);
    }
    return res;
}
vector<int>v[N];
int main(){
    scanf("%d",&n);
    ll ans=0;
    for(int i=1;i<=n;i++){
        int x;
        scanf("%d",&x);
        v[x].pb(i);
        add(i,1);
    }
    for(int i=1;i<N;i++){
        if(v[i].empty())continue;
        for(int j=0;j<v[i].size();j++){
            int x=v[i][j];
            add(x,-1);
            n--;
        }
        for(int j=0;j<v[i].size();j++){  
            int x=v[i][j];
            ll res=min(cal(x-1),n-cal(x));
            //bug(i,res);
            ans+=res;
        }
    }
    printf("%lld\n",ans);
}
/*
7
3 1 4 1 5 9 2
*/

 

 

转载于:https://www.cnblogs.com/ccsu-kid/p/10599346.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值