[树状数组]JZOJ 4658 小Z调顺序

Description

 

Input

Output

 

Sample Input

3 1
2 2 1

Sample Output

1
 

Data Constraint

分析

简单的树状数组求逆序对,答案等于逆序对数-k,注意当k大于逆序对数输出零

 

#include <iostream>
#include <cstdio>
#include <memory.h>
#include <algorithm>
#define lowbit(x) x&-x
using namespace std;
typedef long long ll;
const int N=1e5+10;
ll t[N],a[N],b[N],k;
int n,cnt;

void Add(int x) {
    for (int i=x;i<N;i+=lowbit(i)) t[i]++;
}

ll Query(int x) {
    ll ans=0;
    for (int i=x;i;i-=lowbit(i)) ans+=t[i];
    return ans;
}

int main() {
    scanf("%d%lld",&n,&k);
    for (int i=1;i<=n;i++) scanf("%lld",&a[i]);
    memcpy(b,a,sizeof b);sort(b+1,b+n+1);cnt=unique(b+1,b+n+1)-b-1;
    for (int i=1;i<=n;i++) a[i]=lower_bound(b+1,b+cnt+1,a[i])-b;
    ll ans=0;
    for (int i=n;i;i--) {
        ans+=Query(a[i]-1);Add(a[i]);
    }
    printf("%lld",max(ans-k,0ll));
}
View Code

 

posted @ 2019-04-25 20:02  Vagari  阅读(119)  评论(0编辑  收藏  举报