Problem Description
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) which 1≤i<j≤n and ai>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≤100000 , numbers in the sequence are in [−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
题解:每一个逆序对需要支付x yuan,而用技巧y yuan可以消除一个逆序对,所以最小花费就是逆序对数乘以min(x,y);
求解逆序对,使用递归的方式对数据进行排查,分为前部分和后部分,再不断递归,直至不能分解,然后查询是否有逆序,进行累加后,对当前数据归并排序,返回上一层。
时间复杂度O(nlogn);
#include<iostream>
#define maxn 1000001
using namespace std;
long long a[maxn],b[maxn],counts=0;
void Merge(int sta,int mid,int en)
{
int i=sta,j=mid+1,k=sta;
while(i<=mid&&j<=en)
{
if(a[i]<=a[j])
{
b[k++]=a[i++];
}
else
{
counts+=(j-k);//逆序数累加
b[k++]=a[j++];
}
}
while(i<=mid)
{
b[k++]=a[i++];
}
while(j<=en)
{
b[k++]=a[j++];
}
for(int s=sta;s<=en;s++)//将b内排好序的数据导入a
{
a[s]=b[s];
}
}
void MergeSort(int sta,int en)
{
if(sta<en)
{
int mid=(sta+en)/2;
MergeSort(sta,mid);//分解数组(前半部分)
MergeSort(mid+1,en);//(后半部分)
Merge(sta,mid,en);//不能分解时开始归并
}
return ;
}
int main()
{
int n,x,y;
while(cin>>n>>x>>y)
{
for(int i=0;i<n;i++)
{
cin>>a[i];
}
MergeSort(0,n-1);
cout<<counts*min(x,y)<<endl;
}
}