求逆序对的方法有暴力,归并,分治,线段树,树状数组等等,这里讲怎么用线段树求解。
以求 1,3,2,4 为例, 用暴力的方法求逆序数的话,主要是枚举每一个逆序对,比如枚举1 的后面有多少个数与它成逆序对,再枚举3。。。那么假如知道1的后面有多少个数是与它成逆序数的,不就可以更快的求解了吗?
首先,很明显,枚举一个数前面有多少个数与其成逆序对算出来的结果与枚举其后面的数算出来的结果是一样的,因此,在算给定序列的逆序数的时候,那么第i个数的逆序数就是前i-1个数中比它大的数的个数,那么这些个数如何求呢,我们可以设置一个区间[1,N],初始化为0,在i之前出现的每一个数都在对应位置加1,那么第i个数的逆序数就等于[i,N]这个区间的和,求和用线段树实现就可。
然后是对于本题,若abcde...的逆序数为k,那么bcde...a的逆序数是多少?我们假设abcde...中小于a的个数为t , 那么大于a的个数就是n-t-1,当把a移动最右位时,原来比a大的现在都成了a的逆序对,即逆序数增加n-t-1,但是原来比a小的构成逆序对的数,现在都变成了顺序,因此逆序对减少t ,所以新序列的逆序数为 k +=n - t - t -1,即k += n-1-2 * t , 于是我们只要不断移位(n次),然后更新最小值就可以了。
代码如下:
#include <cstdio>
#include <stack>
#include <set>
#include <iostream>
#include <string>
#include <vector>
#include <queue>
#include <list>
#include <functional>
#include <cstring>
#include <algorithm>
#include <cctype>
#include <string>
#include <map>
#include <iomanip>
#include <cmath>
#define LL long long
#define ULL unsigned long long
#define SZ(x) (int)x.size()
#define Lowbit(x) ((x) & (-x))
#define MP(a, b) make_pair(a, b)
#define MS(arr, num) memset(arr, num, sizeof(arr))
#define PB push_back
#define F first
#define S second
#define ROP freopen("input.txt", "r", stdin);
#define MID(a, b) (a + ((b - a) >> 1))
#define LC rt << 1, l, mid
#define RC rt << 1|1, mid + 1, r
#define LRT rt << 1
#define RRT rt << 1|1
#define BitCount(x) __builtin_popcount(x)
#define BitCountll(x) __builtin_popcountll(x)
#define LeftPos(x) 32 - __builtin_clz(x) - 1
#define LeftPosll(x) 64 - __builtin_clzll(x) - 1
const double PI = acos(-1.0);
const int INF = 0x3f3f3f3f;
using namespace std;
const double eps = 1e-5;
const int MAXN = 300 + 10;
const int MOD = 1000007;
const double M=1e-8;
const int N=1e6+10;
typedef pair<int, int> pii;
typedef pair<int, string> pis;
const int d[4][2]={{0,1},{0,-1},{-1,0},{1,0}};
int n,m,st[N],a[N];
void updata(int k)
{
k+=n-1;
st[k]++;
while(k>0) {
k>>=1;
st[k]=st[k<<1]+st[k<<1|1];
}
}
int query(int a,int b,int rt,int l,int r)
{
int i,j;
if (b<=l || r<=a) return 0;
if (a<=l && r<=b) return st[rt];
else {
int u=query(a,b,rt<<1,l,(l+r)>>1);
int v=query(a,b,rt<<1|1,(l+r)>>1,r);
return u+v;
}
}
int main()
{
int i,j;
while(~scanf("%d",&n))
{
MS(st,0);
int r=n,sum=0,res=0,t;
n=1;
while(n<r) n*=2;
for (i=0;i<r;i++) {
scanf("%d",a+i);
a[i]++;
sum+=query(a[i],n+1,1,1,n+1);
updata(a[i]);
}
res=sum;
for (i=0;i<r;i++) {
a[i]--;
sum=sum-a[i]-1+r-a[i];
res=min(res,sum); // 更新新的序列的逆序数
}
printf("%d\n",res);
}
}