HDU 1394 Minimum Inversion Number (tree array | Line Segment tree)
Question link: Click the open link
For the problem of calculating the number of reverse orders, we usually use a line segment tree or a tree array for maintenance. The tree array code is short and easy to write. Try to write a tree array.
First, find the number of reverse orders in the original arrangement. For each operation, because the first number in the current arrangement is obtained to the last position, the answer increases the number of all numbers larger than him, reduces the number of all numbers smaller than him.
For details, see the code:
#include
#include
#include#include
#include
#include
#include
#include
#include
#include
#include
#include
#include
#include
#include
#define Max(a,b) ((a)>(b)?(a):(b))#define Min(a,b) ((a)<(b)?(a):(b))using namespace std;typedef long long ll;const double PI = acos(-1.0);const double eps = 1e-6;const int INF = 1000000000;const int maxn = 5000+10;int T,n,m,bit[maxn],a[maxn];int sum(int x) { int ans = 0; while(x > 0) { ans += bit[x]; x -= x & -x; } return ans;}void add(int x, int d) { while(x <= n) { bit[x] += d; x += x & -x; }}int main() { while(~scanf("%d",&n)) { memset(bit, 0, sizeof(bit)); int ans = 0; for(int i=1;i<=n;i++) { scanf("%d",&a[i]); a[i]++; ans += sum(n) - sum(a[i]); add(a[i], 1); } int cur = ans; for(int i=1;i