small_Dongpo @ 2024-07-11 13:50:38
#include <iostream>
#include <cstdio>
#include <algorithm>
using namespace std;
typedef long long l;
int a[500005], b[500005];
l ans;
#define r register
char inbuf[1 << 20], *st(inbuf), *en(inbuf), outbuf[1 << 20], *outptr(outbuf);
#define g() (((st == en) && (en = (st = inbuf) + fread(inbuf, 1, 1024, stdin))), (st==en)? EOF : *(st++))
#define p(x) (*(outptr++) = (x))
inline int read() {
r int x(0);
r char ch(g());
for(; !isdigit(ch); ch = g());
for(; isdigit(ch); ch = g()) x = (x << 1) + (x << 3) + (ch ^ 48);
return x;
}
void print(r l x) {
r char out[20];
r int len(0);
while (x > 0) {
out[++len] = (x % 10) | 48;
x /= 10;
}
for (r int i(len); i > 0; --i) p(out[i]);
}
void merge(r const int x, r const int y) {
if (x == y) return ;
r const int mid((x + y) >> 1);
merge(x, mid);
merge(mid + 1, y);
r int i(x), j(mid + 1), k(x - 1);
while (i <= mid && j <= y) {
if (a[i] <= a[j]) {
b[++k] = a[i++];
} else {
b[++k] = a[j++];
ans += mid - i + 1;
}
}
while (i <= mid) {
b[++k] = a[i++];
}
while (j <= y) {
b[++k] = a[j++];
}
for (r int i(x); i <= y; ++i) {
a[i] = b[i];
}
}
int main() {
r l n(read());
for (r int i(1); i <= n; ++i) {
a[i] = read();
}
merge(1, n);
printf("%lld", ans);
}
by Dino_tang @ 2024-07-11 21:53:49
本蒟蒻用了归并排序,仅供参考,不得抄袭
#include <bits/stdc++.h>
using namespace std;
typedef long long LL;
const int N = 1000005;
int n;
int a[N],tmp[N];
LL merge_sort (int a[],int l,int r) {
if (l == r) return 0;
int mid = l + r >> 1;
LL ans = merge_sort (a,l,mid) + merge_sort (a,mid + 1,r);
int i = l,j = mid + 1,k = 1;
while (i <= mid && j <= r) {
if (a[i] <= a[j]) tmp[k++] = a[i++];
else tmp[k++] = a[j++],ans += mid - i + 1;
}
while (i <= mid) tmp[k++] = a[i++];
while (j <= r) tmp[k++] = a[j++];
for (int i = 1,j = l;j <= r;i++,j++) a[j] = tmp[i];
return ans;
}
int main () {
cin >> n;
for (int i = 1;i <= n;i++) cin >> a[i];
cout << merge_sort (a,1,n) << endl;
return 0;
}
by Dino_tang @ 2024-07-11 21:54:58
@small_Dongpo
by small_Dongpo @ 2024-07-11 22:17:04
@Hallow_Deathly ???求调,不是发代码