POJ 2299spa
#include <cstdio> #include <cstring> using namespace std; typedef long long ll; const int N = 5e5+10; int n; ll cnt; int s[N], a[N], tmp[N]; inline void merge_sort(int a[], int l, int r){ if(l == r) return; int mid = (l + r) >> 1; merge_sort(a, l, mid); merge_sort(a, mid + 1, r); int i = l, j = mid + 1, k = 0; while(i <= mid && j <= r){ if(a[i] <= a[j]) tmp[k++] = a[i++]; else tmp[k++] = a[j++], cnt += (ll)mid - i + 1; } while(i <= mid) tmp[k++] = a[i++]; while(j <= r) tmp[k++] = a[j++]; for(i = 0; i < k; i++){ a[i + l] = tmp[i]; } } int main(){ #ifdef ONLINE_JUDGE #else freopen("in.txt", "r", stdin); #endif //ONLINE_JUDGE while(scanf("%d", &n), n){ cnt = 0; for(int i = 1; i <= n; i++){ scanf("%d", &s[i]); a[i] = s[i]; } merge_sort(a, 1, n); printf("%lld\n", cnt); } return 0; }