http://acm.hdu.edu.cn/showproblem.php?pid=5775
Long long ago, there was an integer sequence a.
Tonyfang think this sequence is messy, so he will count the number of inversions in this sequence. Because he is angry, you will have to pay x yuan for every inversion in the sequence.
You don't want to pay too much, so you can try to play some tricks before he sees this sequence. You can pay y yuan to swap any two adjacent elements.
What is the minimum amount of money you need to spend?
The definition of inversion in this problem is pair (i,j)(i,j) which 1≤i<j≤n1≤i<j≤n and ai>ajai>aj.
Input
There are multiple test cases, please read till the end of input file.
For each test, in the first line, three integers, n,x,y, n represents the length of the sequence.
In the second line, n integers separated by spaces, representing the orginal sequence a.
1≤n,x,y≤1000001≤n,x,y≤100000, numbers in the sequence are in [−109,109][−109,109]. There're 10 test cases.
Output
For every test case, a single integer representing minimum money to pay.
Sample Input
3 233 666 1 2 3 3 1 666 3 2 1
Sample Output
0 3
题目大意: 根据给定的代码进行模拟, 输出每个数字在这个冒泡排序算法中所能到达的最右位置和最左位置的差值。
思路: 对于a[i], 若a[i]右侧有k个数小于a[i],那么a[i]肯定要交换k次, 如果我们能够求出a[i]左侧小于a[i]的数的个数sum, 那么a[i]右侧小于a[i]的数个个数k=a[i]-1-sum;(因为a[i]最多有a[i]-1个数小于它), 这个sum我们是可以用树状数组快速求出的,比如在读入一个数a[i]后,我们给大于等于a[i]的位置都加上1,查询的时候直接查询前a[i]项的和即可。(当然要先查询 再修改) 那么i+k就是这个数能达到的最靠右的位置; 最左侧的位置怎么求呢? 我们知道这是一个冒泡排序,设a[i]=t,那么a[i]最终要在位置t上, 若a[i]<t, 那么a[i]一定会右移不会左移, 反正a[i]一定会左移不会右移, 因此最左侧的位置就是min(a[i],i)。 那么这道题就做出来了。
#include<iostream>
#include<cstdio>
#include<cstring>
#include<algorithm>
using namespace std;
int tree[100005];
int re[100005];
int n;
inline int lowbit(int x)
{
return x&(-x);
}
void add(int i)//给>=a[i]的位置上的数都加上1
{
for(;i<=n;i+=lowbit(i))
tree[i]+=1;
}
int sum(int i)//求a[i]左侧小于a[i]的数的个数
{
int s=0;
for(;i;i-=lowbit(i))
s+=tree[i];
return s;
}
int main()
{
int t;
scanf("%d",&t);
int times=0;
while(t--)
{
scanf("%d",&n);
memset(tree,0,sizeof(tree));
int temp;
for(int i=1;i<=n;i++)
{
scanf("%d",&temp);
int cnt=i+temp-1-sum(temp);
re[temp]=cnt-min(temp,i);
add(temp);
}
printf("Case #%d:",++times);
for(int i=1;i<=n;i++)
printf(" %d",re[i]);
printf("\n");
}
return 0;
}