Hdu1394Minimum Inversion Number线段树
这个网上一搜一大堆,就是先求一个,其余的for一遍搞出来。
#include<stdio.h> #include<stdlib.h> #define max 5555 int sum[max * 4]; int min(int a, int b) { if (a>b) return b; else return a; } void fuqin(int a) { sum[a] = sum[a * 2] + sum[a * 2 + 1]; } void build(int l, int r, int a) { void fuqin(int); sum[a] == 0; if (l == r) return; int mid = (l + r) / 2; build(l, mid, a * 2); build(mid + 1, r, a * 2 + 1); fuqin(a); } void up(int q, int l, int r, int a) { void fuqin(int); if (l == r) { sum[a]++; return; } int mid = (l + r) / 2; if (q <= mid) up(q, l, mid, a * 2); else up(q, mid + 1, r, a * 2 + 1); fuqin(a); } int ask(int L, int R, int l, int r, int a) { if (L <= l&&r <= R) return sum[a]; int mid = (l + r) / 2; int ans = 0; if (mid >= L) ans += ask(L, R, l, mid, a * 2); if (mid<R) ans += ask(L, R, mid + 1, r, a * 2 + 1); return ans; } void main() { int n, i, x[5555], ans = 0, q; int min(int, int); void build(int, int, int); void tianjia(int, int, int, int); int ask(int, int, int, int, int); while (scanf("%d", &n) != EOF) { ans = 0; memset(sum, 0, sizeof(sum)); build(0, n - 1, 1); for (i = 0; i<n; i++) { scanf("%d", &x[i]); ans += ask(x[i], n - 1, 0, n - 1, 1); up(x[i], 0, n - 1, 1); } q = ans; for (i = 0; i<n; i++) { q = q + (n - 1 - x[i]) - x[i]; ans = min(q, ans); } printf("%d\n", ans); } }