题意:
不翻译了~
Sherlock's N (1 ≤ N ≤ 100,000) cows are lined up to be milked in the evening. Each cow has a unique "grumpiness" level in the range 1...100,000. Since grumpy cows are more likely to damage Sherlock's milking equipment, Sherlock would like to reorder the cows in line so they are lined up in increasing order of grumpiness. During this process, the places of any two cows (necessarily adjacent) can be interchanged. Since grumpy cows are harder to move, it takes Sherlock a total of X + Y units of time to exchange two cows whose grumpiness levels are X and Y.
Please help Sherlock calculate the minimal time required to reorder the cows.
题解:
每次交换只能相邻交换(冒泡排序)。只不过这里的求的不是最小交换次数(逆序数),而是每个点有个权值,每次交换花费X+Y(X,Y为权值)。求所有的花费最低。和求序列最小逆序数一样,从头扫一遍就行。由于相邻交换,所以每次刚一出现存在逆序的元素都应该立即交换才能保证最小。只不过现在的树状数组要开两个,一个求前面有多少个逆序数,另外一个求前面比它大的元素总和。
#include<bits/stdc++.h>
using namespace std;
const int maxn = 100111;
long long c[2][maxn];
void add(int i,int x,long long v)
{
while(x<maxn)
{
c[i][x] += v;
x+=(x&-x);
}
}
long long sum(int i,int x)
{
long long res = 0;
while(x>0)
{
res+=c[i][x];
x-=(x&-x);
}
return res;
}
int main()
{
int n;
cin>>n;
//memset(c,0,sizeof c);
long long ans=0;
for(int i=1;i<=n;i++)
{
int x;
scanf("%d",&x);
long long q= (i-1-sum(0,x));///多少个值比x大
// long long w= (i-1-sum(1,x));
long long w=sum(1,maxn)-sum(1,x);///比x大的值 和为多少
ans+=q*x+w;
add(0,x,1);
add(1,x,x);
}
cout<<ans<<endl;
}