#include<iostream>
#include<string>
#include<cstring>
#include<cmath>
#include<cstdio>
#include<vector>
#include<queue>
#include<map>
using namespace std;
const int maxn = 5050;
struct SegmentTree{
int left,right,val,mid;
}tr[maxn<<2];
void build(int left,int right,int k){
tr[k].left=left;
tr[k].right=right;
tr[k].mid=(left+right)>>1;
tr[k].val=0;
if(left==right) return;
build(left,tr[k].mid,k<<1);
build(tr[k].mid+1,right,k<<1|1);
}
int query(int left,int right,int k){
if(left<=tr[k].left&&tr[k].right<=right) return tr[k].val;
int res=0;
if(left<=tr[k].mid) res+=query(left,right,k<<1);
if(tr[k].mid<=right) res+=query(left,right,k<<1|1);
return res;
}
void update(int pos,int k){
tr[k].val++;
if(tr[k].left==tr[k].right) return;
if(pos<=tr[k].mid) update(pos,k<<1);
else update(pos,k<<1|1);
}
int main()
{
#ifndef ONLINE_JUDGE //这种输入格式是从Codeforces那边的大神的代码里看到的
freopen("a.in", "r", stdin);
#endif
int n,a[maxn];
while(cin>>n){
build(1,n,1);
int sum=0;
for(int i=0;i<n;i++){
cin>>a[i];
sum+=query(a[i]+1,n,1); //用线段树求出已加入的数中比当前值大的数有多少个
update(a[i],1); //加入线段树
}
int ans=sum;
for(int i=0;i<n;i++){
sum=sum-a[i]+(n-a[i]-1);
if(ans>sum) ans=sum;
}
cout<<ans<<endl;
}
return 0;
}
下面是树状数组算法,比起线段树较容易写,思想是一致的
#include<iostream>
#include<string>
#include<cstring>
#include<cmath>
#include<cstdio>
#include<vector>
#include<queue>
#include<map>
using namespace std;
const int maxn = 5050;
int cnt[maxn],n;
int numLowBit(int x){return x&(-x);}
void update(int x){
for(int i=x;i<=n;i+=numLowBit(i))
cnt[i]++;
}
int query(int x){
int sum=0;
for(int i=x;i>0;i-=numLowBit(i))
sum+=cnt[i];
return sum;
}
int main()
{
#ifndef ONLINE_JUDGE
freopen("a.in", "r", stdin);
#endif
int a[maxn];
while(cin>>n){
memset(cnt,0,sizeof(cnt));
int sum=0;
for(int i=0;i<n;i++){
cin>>a[i];
a[i]++;
sum+=i-query(a[i]);
update(a[i]);
}
int ans=sum;
for(int i=0;i<n;i++){
sum=sum-a[i]+1+(n-a[i]);
if(ans>sum) ans=sum;
}
cout<<ans<<endl;
}
return 0;
}