http://acm.hdu.edu.cn/showproblem.php?pid=1394 #includestdio.h#includestdlib.h#includestring.h#includemath.h#includeiostream#includealgorithmusing namespace std;const int sizen=100000;int a[sizen];struct ele{ int left; int right; int sum;}p
http://acm.hdu.edu.cn/showproblem.php?pid=1394
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
#include<math.h>
#include<iostream>
#include<algorithm>
using namespace std;
const int sizen=100000;
int a[sizen];
struct ele
{
int left;
int right;
int sum;
}p[sizen*4];
void build(int L,int R,int step)
{
p[step].sum=0;
p[step].left=L;
p[step].right=R;
if(L!=R)
{
int Mid=(L+R)>>1;
build(L,Mid,2*step);
build(Mid+1,R,2*step+1);
}
}
void update(int x,int step)
{
if(p[step].left==p[step].right)
p[step].sum=1;
else
{
int Mid=(p[step].left+p[step].right)>>1;
if(x<=Mid)
update(x,2*step);
else
update(x,2*step+1);
p[step].sum=p[2*step].sum+p[2*step+1].sum;
}
}
int get(int x,int y,int step)
{
if(p[step].left==x&&p[step].right==y)
return p[step].sum;
else
{
int Mid=(p[step].left+p[step].right)>>1;
if(y<=Mid)
return get(x,y,2*step);
else
if(x>=Mid+1)
return get(x,y,2*step+1);
else
return get(x,Mid,2*step)+get(Mid+1,y,2*step+1);
}
}
int main()
{
int n;
int i;
int sum,Min;
while(scanf("%d",&n)!=EOF)
{
sum=0;
build(1,n,1);
for(i=1;i<=n;i++)
{
scanf("%d",&a[i]);
if(a[i]+2<=n)
sum+=get(a[i]+2,n,1);
update(a[i]+1,1);
}
Min=sum;
for(i=1;i<n;i++)
{
sum-=a[i];
sum+=(n-1-a[i]);
if(sum<Min)
Min=sum;
}
printf("%d\n",Min);
}
return 0;
}
【感谢龙石为本站数据质量管理平台提供技术支撑 http://www.longshidata.com/pages/quality.html】