先上题目
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元,或者选择相邻的元素进行交换一次交换要收y元。求最少的花费情况。
分析:首先根据题目我们可以得出每进行一次交换只能交换一对逆序对。所以求最小的花费就是求逆序对的个数*x,y中较小的那一个。
对于求逆序对的方法有很多这里我们采用比较好理解的并归搜索,具体方法这里不过多论述直接上代码。
#include <iostream>
#include <algorithm>
#include <cstdio>
using namespace std;
long long a[100005];
long long b[100005];
long long sum=0;
int main()
{
void bsort(long long l,long long r);
long long n,x,y;
while(~scanf("%lld%lld%lld",&n,&x,&y)){
sum=0;
for(long long i=1;i<=n;i++){
scanf("%lld",&a[i]);
}
bsort(1,n);
long long res=sum*min(x,y);
printf("%lld\n",res);
}
}
void bsort(long long l,long long r)
{
long long mid,tmp,i,j;
if(r>l+1){
mid=(l+r)/2;
bsort(l,mid-1);
bsort(mid,r);
tmp=l;
for(i=l,j=mid;i<=mid-1&&j<=r;){
if(a[i]>a[j]){
b[tmp++]=a[j++];
sum+=(mid-i);
}
else{
b[tmp++]=a[i++];
}
}
if(j<=r)
for(;j<=r;j++){
b[tmp++]=a[j];
}
else
for(;i<=mid-1;i++){
b[tmp++]=a[i];
}
for(i=l;i<=r;i++){
a[i]=b[i];
}
}
else{
if(r==l+1)
if(a[l]>a[r]){
swap(a[l],a[r]);
sum++;
}
}
}
注意:首先题目中输入必须采用scanf否则会超时,然后因为多组输入必须每次输入后对sum清零。