题目大意:
就是求逆序对之后O(1)递推每一种变化对应的逆序对数量的最小值
大致思路:
....刷
代码如下:
Result : Accepted Memory : 1644 KB Time : 93 ms
/* * Author: Gatevin * Created Time: 2015/8/14 22:01:45 * File Name: Sakura_Chiyo.cpp */ #include<iostream> #include<sstream> #include<fstream> #include<vector> #include<list> #include<deque> #include<queue> #include<stack> #include<map> #include<set> #include<bitset> #include<algorithm> #include<cstdio> #include<cstdlib> #include<cstring> #include<cctype> #include<cmath> #include<ctime> #include<iomanip> using namespace std; const double eps(1e-8); typedef long long lint; #define maxn 5050 struct Segment_Tree { #define lson l, mid, rt << 1 #define rson mid + 1, r, rt << 1 | 1 int val[maxn << 2]; void pushUp(int rt) { val[rt] = val[rt << 1] + val[rt << 1 | 1]; return; } void build(int l, int r, int rt) { if(l == r) { val[rt] = 0; return; } int mid = (l + r) >> 1; build(lson); build(rson); pushUp(rt); } void update(int l, int r, int rt, int pos, int value) { if(l == r) { val[rt] += value; return; } int mid = (l + r) >> 1; if(mid >= pos) update(lson, pos, value); else update(rson, pos, value); pushUp(rt); return; } int query(int l, int r, int rt, int L, int R) { if(l >= L && r <= R) return val[rt]; int mid = (l + r) >> 1; int ret = 0; if(mid >= L) ret += query(lson, L, R); if(mid + 1 <= R) ret += query(rson, L, R); return ret; } }; Segment_Tree ST; int a[maxn]; int main() { int n; while(~scanf("%d", &n)) { ST.build(1, n + 1, 1); int sum = 0; for(int i = 1; i <= n; i++) { scanf("%d", &a[i]); a[i]++; sum += ST.query(1, n + 1, 1, a[i] + 1, n + 1); ST.update(1, n + 1, 1, a[i], 1); } int ans = sum; for(int i = 1; i <= n; i++) { sum += (n - a[i]); sum -= (a[i] - 1); ans = min(ans, sum); } printf("%d\n", ans); } return 0; }