归并排序之逆序对
题目传送:#1141 : 二分·归并排序之逆序对
好吧,第一次手敲归并,略挫,不过爆intWA了一发
AC代码:
#include <map>
#include <set>
#include <list>
#include <cmath>
#include <deque>
#include <queue>
#include <stack>
#include <bitset>
#include <cctype>
#include <cstdio>
#include <string>
#include <vector>
#include <complex>
#include <cstdlib>
#include <cstring>
#include <fstream>
#include <sstream>
#include <utility>
#include <iostream>
#include <algorithm>
#include <functional>
#define LL long long
#define INF 0x7fffffff
using namespace std;
int a[100005];
int n;
LL ans;//好吧,会爆int
int tmp[100005];
void merge_sort(int s, int t) {
if(s == t) return;
int mid = (s + t) >> 1;
merge_sort(s, mid);
merge_sort(mid + 1, t);
int cnt = 0;
int i, j;
for(i = s, j = mid + 1; i <= mid && j <= t; ) {
if(a[i] > a[j]) {
tmp[cnt ++] = a[j];
j ++;
ans += (mid - i + 1);
}
else {
tmp[cnt ++] = a[i];
i ++;
}
}
while(i <= mid) {
tmp[cnt ++] = a[i ++];
}
while(j <= t) {
tmp[cnt ++] = a[j ++];
}
for(int i = s, j = 0; i <= t && j <= cnt; i ++, j ++) {
a[i] = tmp[j];
}
}
int main() {
scanf("%d", &n);
for(int i = 1; i <= n; i ++) {
scanf("%d", &a[i]);
}
ans = 0;
merge_sort(1, n);
printf("%lld\n", ans);//注意这里用%I64d会PE,或者用cout也行
//cout << ans << endl;
return 0;
}
版权声明:本文为博主原创文章,未经博主允许不得转载。
时间: 2024-10-06 22:23:19