Inverse Pair[牛客]

题目传送门

For a sequence \(t_{1...n}\)we define the weight of it is the number of pairs \((i,j)\)satisfy \(i<j\) and \(t_i>t_j\)
Now give you a permutation a_{1...n} , you need to choose a sequence b_{1...n}satisfies b_i∈{0,1} to minimize the weight of sequence c_{1...n}which satisfies c_i=ai+bi.

分析:

考虑什么时候会使weight减小,应该是x+1在x前面的时候.因为如果x+2在x前面,就算x++也不会改变逆序对数.

所以,如果x+1在x前面,x必须+1.

如果x不加1,不仅x这一位少了一个使weight减1的机会,后面的答案也不会改变.(x+1不会让后面的逆序对变多),所以这是一个无后效性的贪心.

code

#include <bits/stdc++.h>
using namespace std;
const int N=2e5+5;
#define lb(x) (x&(-x))
int c[N];int n;bool used[N];
void update(int x){
    for (;x<=n;x+=lb(x)) c[x]++;
}
int query(int x){
    int s=0;for (;x;x-=lb(x))s+=c[x];return s;
}
#undef lb
int main() {
    scanf ("%d",&n);long long ans=0;
    for (int i=1,x;i<=n;i++) {
        scanf ("%d",&x);
        if (used[x+1]) x++;
        ans+=i-1-query(x),update(x);
        used[x]=1;
    }
    printf ("%lld",ans);
    return 0;
}

posted @ 2021-07-27 21:22  GUO_dx  阅读(41)  评论(0编辑  收藏  举报