#include<stdio.h>
int main()
{
int n,i,a[5024],j,sum,mixx;
while(~scanf("%d",&n))
{
for(i=1;i<=n;i++)
scanf("%d",&a[i]);
sum=0;
for(i=1;i<=n;i++)
for(j=i+1;j<=n;j++)
if(a[i]>a[j]) sum++;
mixx=sum;
for(i=n;i>0;i--)
{
sum-=n-1-a[i];
sum+=a[i];
if(sum<mixx)
mixx=sum;
}
printf("%d
",mixx);
}
return 0;
}
#include <stdio.h>
#include <string.h>
#include <iostream>
#include <algorithm>
#include <vector>
#include <queue>
#include <set>
#include <map>
#include <string>
#include <math.h>
#include <stdlib.h>
#include <time.h>
using namespace std;
const int N=5000+5;
int p[N];
int lowbit(int x)
{
return x&-x;
}
int sum(int x)
{
int ret=0;
while(x>0)
{
ret+=p[x];
x-=lowbit(x);
}
return ret;
}
void add(int x,int d)
{
while(x<=N)
{
p[x]+=d;
x+=lowbit(x);
}
}
int main()
{
int n,i,a[5005],ans,mixx;
while(~scanf("%d",&n))
{
memset(p,0,sizeof(p));
ans=0;
for(i=1;i<=n;i++)
{
scanf("%d",&a[i]);
ans+=n-1-a[i]-sum(a[i]+1);
add(a[i]+1,1);
}
mixx=ans;
for(i=n;i>=1;i--)
{
ans-=n-1-a[i];
ans+=a[i];
mixx=min(mixx,ans);
}
printf("%d
",mixx);
}
return 0;
}
线段树版本
/* ***********************************************
Author :xryz
Email :523689985@qq.com
Created Time :5-1 16:27:06
File Name :Minimum Inversion Number�߶����汾.cpp
************************************************ */
#include <stdio.h>
#include <string.h>
#include <iostream>
#include <algorithm>
#include <vector>
#include <queue>
#include <set>
#include <map>
#include <string>
#include <math.h>
#include <stdlib.h>
#include <time.h>
using namespace std;
const int N=5000+2;
int a[N],cnt,n;
struct Tree
{
int left,right;
int sum;
} tree[4*N+10];
int query(int id,int l,int r)
{
if(tree[id].left==l&&tree[id].right==r)
return tree[id].sum;
else
{
int mid=(tree[id].left+tree[id].right)/2;
if(r<=mid) return query(id*2,l,r);
else if(l>mid) return query(id*2+1,l,r);
else
return query(id*2,l,mid)+query(id*2+1,mid+1,r);
}
}
void update(int id,int pos,int val)
{
if(tree[id].left==tree[id].right)
{
tree[id].sum=val;
return ;
}
else
{
int mid=(tree[id].left+tree[id].right)/2;
if(pos<=mid) update(id*2,pos,val);
else update(id*2+1,pos,val);
tree[id].sum=tree[id*2].sum+tree[id*2+1].sum;
}
}
void build(int id,int l,int r)
{
tree[id].left=l;
tree[id].right=r;
if(l==r)
{
tree[id].sum=0;
}
else
{
int mid=(l+r)/2;
build(id*2,l,mid);
build(id*2+1,mid+1,r);
tree[id].sum=tree[id*2].sum+tree[id*2+1].sum;
}
}
int main()
{
int i,minx;
while(~scanf("%d",&n))
{
//a[0]=0;
//memset(a,0,sizeof(a));
build(1,1,n);
cnt=0;
for(i=1; i<=n; i++)
{
scanf("%d",&a[i]);
cnt+=n-1-a[i]-query(1,1,a[i]+1);
update(1,a[i]+1,1);
//printf("%d
",cnt);
}
minx=cnt;
for(i=n; i>0; i--)
{
cnt-=n-1-a[i];
cnt+=a[i];
minx=min(minx,cnt);
}
printf("%d
",minx);
}
return 0;
}
版权声明:本文为博主原创文章,未经博主允许不得转载。http://xiang578.top/