hihoCoder#1141 二分·归并排序之逆序对

原题地址

 

又是一道WA成狗的题,最后发现原来是结果溢出了。。

 

代码:

 1 #include <iostream>

 2 #include <cstring>

 3 

 4 using namespace std;

 5 

 6 #define MAX_N 100008

 7 

 8 int N;

 9 long long a[MAX_N];

10 long long b[MAX_N];

11 

12 long long count(int l, int r) {

13   if (l >= r)

14     return 0;

15 

16   long long res = 0;

17   int m = (l + r) / 2;

18   res += count(l, m);

19   res += count(m + 1, r);

20   int i = l;

21   int j = m + 1;

22   int k = 0;

23   while (i <= m && j <= r) {

24     if (a[i] <= a[j]) {

25       b[k++] = a[i++];

26     }

27     else {

28       res += (m - i + 1);

29       b[k++] = a[j++];

30     }

31   }

32   while (i <= m)

33     b[k++] = a[i++];

34   while (j <= r)

35     b[k++] = a[j++];

36 

37   while (k--)

38     a[l + k] = b[k];

39   return res;

40 }

41 

42 int main() {

43   scanf("%d", &N);

44   for (int i = 0; i < N; i++)

45     scanf("%lld", &(a[i]));

46   printf("%lld\n", count(0, N - 1));

47   return 0;

48 }

 

你可能感兴趣的:(code)