Topic link: https://vjudge.net/problem/HDU-1394
The reverse number of a given number sequence a1, a2,..., an is a logarithm satisfying I < J and AI > AJ (ai, aj). For a given number sequence a1, a2,..., an, if we move the first m > = 0 number to the end of the seqence, we will get another sequence. In total, there are the following sequences:
a1, a2,..., an-1, an (where m = 0-initial sequence)
a2, a3,..., an, a1 (where m = 1)
a3, a4,..., an, a1, a2 (where m = 2)
...
An, a1, a2,..., an-1 (where m = n-1)
You are asked to write a program to find the minimum number of inversions in the above sequence.
Analysis: This problem data is not big, direct violence can also be found, here, we use a more efficient method - line segment tree to solve. In fact, only one thing is clear: if the initial inverse logarithm has been found, then when the first item is put i n the last inverse logarithm k will become k-a[i]+n-1-a[i].
#include <iostream> #include <algorithm> #include <cstdio> #include <cstring> #include <cmath> #define L(u) (u<<1) #define R(u) (u<<1|1) using namespace std; const int maxn=5005; const int INF=0x3f3f3f3f; int a[maxn]; struct Node { int l,r; int num; } node[maxn<<2]; void Pushup(int u) { node[u].num=node[L(u)].num+node[R(u)].num; return; } void Build(int u,int left,int right) { node[u].l=left; node[u].r=right; if(left==right) { node[u].num=0; return; } int mid=(left+right)>>1; Build(L(u),left,mid); Build(R(u),mid+1,right); Pushup(u); } int Quary(int u,int left,int right) { if(left==node[u].l&&right==node[u].r) return node[u].num; int mid=(node[u].l+node[u].r)>>1; if(mid>=right) return Quary(L(u),left,right); else if(mid<left) return Quary(R(u),left,right); else return Quary(L(u),left,mid)+Quary(R(u),mid+1,right); } void Update(int u,int val) { if(node[u].l==node[u].r) { node[u].num++; return; } int mid=(node[u].l+node[u].r)>>1; if(mid>=val) Update(L(u),val); else Update(R(u),val); Pushup(u); } int main() { //freopen("in.txt","r",stdin); int n; while(~scanf("%d",&n)) { for(int i=0; i<n; i++) scanf("%d",a+i); Build(1,0,n-1); int sum=0,ans=INF; for(int i=0; i<n; i++) { sum+=Quary(1,a[i],n-1); Update(1,a[i]); } ans=min(ans,sum); for(int i=0; i<n; i++) { sum=sum-a[i]+n-1-a[i]; ans=min(ans,sum); } printf("%d\n",ans); } return 0; }