Time Limit: 1000 MS Memory Limit: 30000 KB
64-bit integer IO format: %I64d , %I64u Java class name: Main
4 4 2 8 0 3 10 0 1 2 3 4 5 6 7 8 9 6 -42 23 6 28 -100 65537 5 0 0 0 0 0
Scenario #1: 3 Scenario #2: 0 Scenario #3: 5 Scenario #4: 0
#include<iostream> #include<cstdio> #include<stdlib.h> #define N 1000010 using namespace std; long long ans; int a[N]; void merge(int s1,int e1,int s2,int e2) { int p1,p2,p; int* temp = new int[e2-s1+5]; p=0;p1=s1;p2=s2; while(p1<=e1&&p2<=e2) { if(a[p1]<=a[p2]) { temp[p++]=a[p1++]; continue; } else { temp[p++]=a[p2++]; ans+=e1-p1+1; //关键所在 continue; } } while(p1<=e1) temp[p++]=a[p1++]; while(p2<=e2) temp[p++]=a[p2++]; int i; for(i=s1;i<=e2;i++) a[i]=temp[i-s1]; delete temp; } void merge_sort(int s,int e) { int m; if(s<e) { m=(s+e)/2; merge_sort(s,m); merge_sort(m+1,e); merge(s,m,m+1,e); } } int main() { int test; int num; scanf("%d",&test); for(num=1;num<=test;num++) { int n,i; ans=0; scanf("%d",&n); for(i=0;i<n;i++) scanf("%d",&a[i]); merge_sort(0,n-1); printf("Scenario #%d:\n",num); printf("%lld\n",ans); if(num!=test) printf("\n"); } }
#include<iostream> #include<cstring> #include <stdio.h> #include<algorithm> using namespace std; int n; int static c[500003]; int a[500003]; const int maxn = 500003; struct Node { int value,pos; bool operator<(const Node a)const { return value<a.value; } } s[500003]; int lowbit(int x) { return x&(-x); } void insert(int pos,int x) { while(pos<=maxn) { c[pos]+=x; pos+=lowbit(pos); } } int sum(int x) { int s=0; while(x>0) { s+=c[x]; x-=lowbit(x); } return s; } int main() { int t,num; cin>>t; for(num=1; num<=t; num++) { scanf("%d",&n); memset(c,0,sizeof(c)); memset(a,0,sizeof(a)); for(int i=0; i<n; i++) { scanf("%d",&s[i].value); s[i].pos=i+1; } sort(s,s+n); int id=1; a[s[0].pos]=1; for(int i=1; i<n; i++) //离散化 { if(s[i].value!=s[i-1].value) { a[s[i].pos]=++id; } else { a[s[i].pos]=id; } } long long int ans=0; for(int i=1; i<=n; i++) //一个个插入求逆序对 { insert(a[i],1); ans+=(i-sum(a[i])); } printf("Scenario #%d:\n",num); printf("%lld\n",ans); if(num!=t) printf("\n"); } return 0; }
树状数组时间空间上都没有归并好~~~~~~~
原文:http://www.cnblogs.com/zhangying/p/3995496.html