归并排序:
#include <iostream> #include <vector> using namespace std; vector<int>input,tmp(500005); long long result; void Merge(int left, int middle, int right) { int i, j, k; i = left, j= middle+1, k = 1; while(i<= middle && j <= right) { if(input[j] < input[i]) { tmp[k++] = input[j++]; result += middle - i + 1; } else tmp[k++] = input[i++]; } while(i <= middle) tmp[k++] = input[i++]; while(j <= right) tmp[k++] = input[j++]; for(i = left, k = 1; i<= right; i++, k++) input[i] = tmp[k]; } void MergeSort(int left, int right) { if(right > left) { int middle = (right + left) / 2; MergeSort(left,middle); MergeSort(middle+1,right); Merge(left,middle,right); } } int main() { int m,n; while(cin>>n) { if(n==0) break; for(int i=0;i<n;i++) { cin>>m; input.push_back(m); } result = 0; MergeSort(0,n-1); cout<<result<<endl; input.clear(); } }树状数组:
#include <iostream> #include <cstring> using namespace std; const int MAXN = 10005; int in[MAXN]; int n; int LowBit(int t) { return t&(-t); } int GetSum(int end) { int sum = 0; while(end > 0) { sum += in[end]; end -= LowBit(end); } return sum; } void Plus(int pos, int num) { while(pos <= n) { in[pos] += num; pos += LowBit(pos); } } int main() { int x,sum; while(cin>>n) { memset(in,0,sizeof(in)); sum = 0; for(int i=1;i<=n;i++) { cin>>x; sum += GetSum(n) - GetSum(x); Plus(x,1); } cout<<sum<<endl; } }