aldol_reaction @ 2020-11-03 21:56:09
#include<cstdio>
#include<iostream>
#include<cstring>
#include<string>
#include<algorithm>
#include<cmath>
#include<vector>
#include<queue>
#include<map>
#include<stack>
#include<set>
using namespace std;
typedef long long ll;
#define maxn 500005
int a[maxn], t[maxn], n;
ll ans;
void mergeSort(int l, int r) {
if(l == r) return;
int mid = (l+r) / 2;
mergeSort(l, mid);
mergeSort(mid+1, r);
int p = l, q = mid+1, i = l;
while(p <= mid && q <= r) {
if(a[p] < a[q]) t[i++] = a[p++];
else {
ans += mid-p+1;
t[i++] = a[q++];
}
}
while(p <= mid) t[i++] = a[p++];
while(q <= r) t[i++] = a[q++];
for(int i = l; i <= r; i++) a[i] = t[i];
}
void inp(void) {
scanf("%d", &n);
for(int i = 1; i <= n; i++) scanf("%d", &a[i]);
}
int main() {
inp();
mergeSort(1, n);
cout << ans;
return 0;
}
by Rui_R @ 2020-11-03 22:04:50
@aldol_reaction
if(a[p] < a[q])
改成
if(a[p]<=a[q])
by aldol_reaction @ 2020-11-04 08:09:24
@Rui_R 谢谢dalao!qwq
by aldol_reaction @ 2020-11-04 08:21:16
@Rui_R 可不可以问下julao,mergeSort函数最后for循环赋值为什么不能改成:
memcpy(a, t, sizeof(a));
by Rui_R @ 2020-11-04 08:27:53
@aldol_reaction 因为那个for只赋值了已经处理好的t的部分(l到r)
但是memcpy把整个t都给了a;举个例子,递归到倒数第二层时,t只在l到r有意义,其余都是0
by aldol_reaction @ 2020-11-04 17:03:31
@Rui_R 蒟蒻懂了!谢谢dalao(鞠躬