标签:des style http java color os
3 2 3 1
7HintInput Details Three cows are standing in line with respective grumpiness levels 2, 3, and 1. Output Details 2 3 1 : Initial order. 2 1 3 : After interchanging cows with grumpiness 3 and 1 (time=1+3=4). 1 2 3 : After interchanging cows with grumpiness 1 and 2 (time=2+1=3).
题意:给出一组数从1到N打乱,要求把数组重新有序(从小到大),只能交换相邻的两个数字,代价为相邻两个数字和。求最小代价?
一个数字必须和前面比它大的数字交换,还要和后面比它小的数字交换。
#include"stdio.h"
#include"string.h"
#define N 100005
#define lowbit(i) (i&(-i))
__int64 a[N]; //记录数字和
int c[N],n; //记录数字个数
void add(int x,int d1,int d2)
{
while(x<=n)
{
a[x]+=d1;
c[x]+=d2;
x+=lowbit(x);
}
}
int sum1(int x) //求比x小的数字已经出现几个(包括x)
{
int s=0;
while(x>0)
{
s+=c[x];
x-=lowbit(x);
}
return s;
}
__int64 sum2(int x)
{
__int64 s=0;
while(x>0)
{
s+=a[x];
x-=lowbit(x);
}
return s;
}
int main()
{
int i,x;
__int64 k1,ans;
while(scanf("%d",&n)!=-1)
{
ans=0;
memset(a,0,sizeof(a));
memset(c,0,sizeof(c));
for(i=1;i<=n;i++)
{
scanf("%d",&x);
add(x,x,1);
k1=i-sum1(x); //x前面有几个比它大的数字
if(k1!=0)
{
ans+=k1*x;
ans+=sum2(n)-sum2(x); //求比x大的数字和
}
}
printf("%I64d\n",ans);
}
return 0;
}
hdu 2838 Cow Sorting(树状数组),布布扣,bubuko.com
标签:des style http java color os
原文地址:http://blog.csdn.net/u011721440/article/details/38067787