3 1 2 2 1 3 0 2 2 1
1 2
//归并排序 109MS 1820K #include<stdio.h> #include<string.h> #define M 100007 #define ll __int64 ll a[M],c[M],ans; void merge(ll a[],int first,int mid,int last,ll c[]) { int i=first,j=mid+1; int m=mid,n=last,k=0; while(i<=m||j<=n) { if(j>n||(i<=m&&a[i]<=a[j]))c[k++]=a[i++]; else {c[k++]=a[j++];ans+=(m-i+1);} } for(i=0;i<k;i++) a[first+i]=c[i]; } void merge_sort(ll a[],int first,int last,ll c[]) { if(first<last) { int mid=(first+last)>>1; merge_sort(a,first,mid,c); merge_sort(a,mid+1,last,c); merge(a,first,mid,last,c); } } int main() { int n; ll k; while(scanf("%d%I64d",&n,&k)!=EOF) { memset(a,0,sizeof(a)); memset(c,0,sizeof(c)); ans=0; for(int i=0;i<n;i++) scanf("%I64d",&a[i]); merge_sort(a,0,n-1,c); if(ans-k<0)printf("0\n"); else printf("%I64d\n",ans-k); } return 0; }
//线段树 546MS 27296K #include<stdio.h> #include<string.h> #include<algorithm> #define M 500007 #define ll __int64 using namespace std; int s[M],n; struct Tree { int l,r,mid; ll val; }tree[M<<1]; struct sa { int id; ll val; }p[M*2]; int cmp(sa a,sa b) { return a.val<b.val; } void build(int left,int right,int i) { tree[i].l=left;tree[i].r=right;tree[i].mid=(left+right)>>1;tree[i].val=0; if(left==right){return;} build(left,tree[i].mid,i*2); build(tree[i].mid+1,right,i*2+1); } int query(int left,int right,int i) { if(left>right)return 0; if(tree[i].l==left&&tree[i].r==right)return tree[i].val; if(right<=tree[i].mid)query(left,right,i*2); else if(left>tree[i].mid)query(left,right,i*2+1); else return query(left,tree[i].mid,2*i)+query(tree[i].mid+1,right,i*2+1); } void insert(int left,int i) { tree[i].val++; if(tree[i].l==tree[i].r)return; if(left<=tree[i].mid)insert(left,2*i); else insert(left,2*i+1); } void discretization() { int tmp=p[1].val,pos=1; for(int i=1;i<=n;i++) if(p[i].val!=tmp)tmp=p[i].val,p[i].val=++pos; else p[i].val=pos; for(int i=1;i<=n;i++) s[p[i].id]=p[i].val; } int main() { __int64 k; while(scanf("%d%I64d",&n,&k)!=EOF) { ll ans=0; build(0,M,1); memset(s,0,sizeof(s)); for(int i=1;i<=n;i++) { scanf("%I64d",&p[i].val); p[i].id=i; } sort(p+1,p+n+1,cmp); discretization(); for(int i=1;i<=n;i++) { ans+=query(s[i]+1,n,1); insert(s[i],1); } if(ans-k<0)printf("0\n"); else printf("%I64d\n",ans-k); } return 0; }
HDU 4911 Inversion 求逆序数对,布布扣,bubuko.com
原文:http://blog.csdn.net/crescent__moon/article/details/38424829