当前位置: 代码迷 >> 综合 >> POJ 2299(归并求逆序对)
  详细解决方案

POJ 2299(归并求逆序对)

热度:84   发布时间:2023-11-25 14:02:18.0

POJ 2299(归并求逆序对)

POJ 2299

#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
#elsefreopen("in.txt", "r", stdin);
#endif //ONLINE_JUDGEwhile(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;
}

 

posted on 2019-03-18 21:47 坤sir 阅读(...) 评论(...) 编辑 收藏