Question: a sequence composed of N non-negative integers, which is the smallest reverse logarithm (1 ≤ n ≤ 10 ^ 5) after a maximum of K adjacent exchanges, 0 ≤ k ≤ 10 ^ 9, 0 ≤ AI ≤ 10 ^ 9 )..
Question link: http://acm.hdu.edu.cn/showproblem.php? PID = 1, 4911
--> Only two adjacent numbers can be exchanged at a time, and only the reverse order of the two numbers is changed at a time. Other numbers do not change the reverse order of the two numbers. Therefore, find all the reverse order pairs, and subtract K from them to be the answer.
#include <cstdio>#include <cstring>#include <algorithm>using namespace std;const int MAXN = 100000 + 10;int n, k;int a[MAXN], b[MAXN];long long C[MAXN];void Init(){ memset(C, 0, sizeof(C));}void Read(){ for (int i = 0; i < n; ++i) { scanf("%d", a + i); }}int Lowbit(int x){ return x & (-x);}long long Sum(int x){ long long nRet = 0; while (x > 0) { nRet += C[x]; x -= Lowbit(x); } return nRet;}void Add(int x){ while (x <= n) { C[x]++; x += Lowbit(x); }}void Solve(){ int nCnt = 0; int nId = 0; long long nReverse = 0; memcpy(b, a, sizeof(a)); sort(b, b + n); nCnt = unique(b, b + n) - b; for (int i = n - 1; i >= 0; --i) { nId = lower_bound(b, b + nCnt, a[i]) - b + 1; nReverse += Sum(nId - 1); Add(nId); } if (nReverse > k) { nReverse -= k; } else { nReverse = 0; } printf("%I64d\n", nReverse);}int main(){ while (scanf("%d%d", &n, &k) == 2) { Init(); Read(); Solve(); } return 0;}
HDU-4911-inversion (discretization + tree array)