HDU4911 Inversion(线段树)

来源:互联网 发布:windows live id格式 编辑:程序博客网 时间:2024/04/28 21:22

Inversion

Time Limit: 2000/1000 MS (Java/Others)    Memory Limit: 131072/131072 K (Java/Others)
Total Submission(s): 4258    Accepted Submission(s): 1561


Problem Description
bobo has a sequence a1,a2,…,an. He is allowed to swap two adjacent numbers for no more than k times.

Find the minimum number of inversions after his swaps.

Note: The number of inversions is the number of pair (i,j) where 1≤i<j≤n and ai>aj.
 

Input
The input consists of several tests. For each tests:

The first line contains 2 integers n,k (1≤n≤105,0≤k≤109). The second line contains n integers a1,a2,…,an (0≤ai≤109).
 

Output
For each tests:

A single integer denotes the minimum number of inversions.
 

Sample Input
3 12 2 13 02 2 1
 

Sample Output
12
 

Author
Xiaoxu Guo (ftiasch)
 

Source
2014 Multi-University Training Contest 5
 

题意:给一个序列,你有k次交换相邻两个数的机会,问k此操作之后逆序对的最小值.

题解:用线段树处理出最开始的逆序数,每次交换选择最大的一个往后移,也就是说每次交换都会减少一个逆序对.结果就是max(0,sum-k).

注意要先离散化.


#include <stdio.h>#include <algorithm>#include <cstring>#include <iostream>#include <cmath>#include <queue>#include <ctype.h>#include <vector>#include <queue>#include <set>#include <map>using namespace std;const long long MAXN=300000+10;const long long INF=1e9+7;#define lson l,m,rt<<1#define rson m+1,r,rt<<1|1long long sum[MAXN<<2];void pushUp(long long rt){    sum[rt]=sum[rt<<1]+sum[rt<<1|1];}void build(long long l,long long r,long long rt){    sum[rt]=0;    if(l==r)        return;    long long m=(l+r)/2;    build(lson);    build(rson);}void update(long long p,long long l,long long r,long long rt){    if(l==r){        sum[rt]++;        return;    }    long long m=(l+r)>>1;    if(p<=m)        update(p,lson);    else        update(p,rson);    pushUp(rt);}long long query(long long L,long long R,long long l,long long r,long long rt){    if(L<=l&&R>=r)        return sum[rt];    long long m=(l+r)>>1;    long long ret=0;    if(L<=m)        ret+=query(L,R,lson);    if(R>m)        ret+=query(L,R,rson);    return ret;}long long a[MAXN];long long b[MAXN];map<long long,long long> m;int main(){    long long n,k;    while(scanf("%lld%lld",&n,&k)!=EOF)    {        m.clear();        long long sum=0;        long long cnt=0;        for(long long i=0;i<n;i++)        {            scanf("%lld",a+i);            b[i]=a[i];        }        sort(b,b+n);        int tot=1;        for(int i=0;i<n;i++){            if(i==0){                m[b[i]]=tot;            }            else if(b[i]==b[i-1]){                m[b[i]]=tot;            }else{                m[b[i]]=++tot;            }        }        build(1,tot,1);        for(int i=0;i<n;i++){            a[i]=m[a[i]];            sum+=query(a[i]+1,tot,1,tot,1);            update(a[i],1,tot,1);        }        if(sum>=k){            printf("%lld\n",sum-k);        }else{            printf("0\n");        }    }}





原创粉丝点击