题目连接:点击打开链接
解题思路:
逆序数模板题。注意此题坑点在于数据大,开成unsigned long long
完整代码:
#include <algorithm> #include <iostream> #include <cstring> #include <complex> #include <cstdio> #include <string> #include <cmath> #include <queue> using namespace std; typedef unsigned long long LL; const int MOD = int(1e9)+7; const int INF = 0x3f3f3f3f; const double EPS = 1e-9; const double PI = acos(-1.0); //M_PI; const int maxn = 2000001; int n; LL p[maxn] , t[maxn] , ans; void merge(int first , int last) { int mid = (first + last) / 2; int i1 = 0 , i2 = first , i3 = mid + 1; while(i2 <= mid && i3 <= last) { if(p[i2] > p[i3]) { t[i1 ++] = p[i3 ++]; ans += mid - i2 + 1; } else t[i1 ++] = p[i2 ++]; } while(i2 <= mid) t[i1 ++] = p[i2 ++]; while(i3 <= last) t[i1 ++] = p[i3 ++]; i1 = first; i2 = 0; while(i2 < last - first + 1) p[i1 ++] = t[i2 ++]; } void merge_sort(int first , int last) { if(first < last) { int mid = (last + first) / 2; merge_sort(first , mid); merge_sort(mid + 1 , last); merge(first , last); } } int main() { #ifdef DoubleQ freopen("in.txt","r",stdin); #endif while(cin >> n) { ans = 0; memset(p , 0 , sizeof(p)); memset(t , 0 , sizeof(t)); for(int i = 0 ; i < n ; i ++) { cin >> p[i]; } merge_sort(0 , n - 1); cout << ans << endl; } return 0; }
原文:http://blog.csdn.net/u013447865/article/details/44782529