2018 Multi-University Training Contest 2 J( Swaps and Inversions)

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交换相邻数字,求最小花费

思路:其实就是m=min(x,y),ans=m*逆序对数。求逆序对数既可以用树状数组也可以归并排序。都可以

const int maxn=1000010;
const int mo=1e9+7;
int a[maxn],b[maxn];
long long sum;
void Merge(int begin,int mid,int end){ //归并
    int i=begin,j=mid+1,pos=begin;
    //对一个个序列排序的过程
    while(i<=mid && j<=end){
        if(a[i]<=a[j]){
            b[pos++]=a[i++];
        }else{
            b[pos++]=a[j++];
            sum+=mid-i+1;//求逆序数
        }
    }
    while(i<=mid) b[pos++]=a[i++];
    while(j<=end) b[pos++]=a[j++];
    for(int i=begin,j=begin;i<=end;i++,j++)
        a[i]=b[j];
}
void Sort(int begin,int end){ //排序
    if(begin<end){
        int mid=(begin+end)/2;
        Sort(begin,mid);
        Sort(mid+1,end);
        //归并
        Merge(begin,mid,end);
    }
}
int main(){
    int t,n;
    ll x,y;
while(scanf("%d%lld%lld",&n,&x,&y)!=EOF){   //求逆序数和
        sum=0;
        for(int i=1;i<=n;i++)
          {  scanf("%d",&a[i]);
          }
            Sort(1,n);
            x=min(x,y);
        printf("%lld\n",sum*x);
    }
    return 0;
}
 

猜你喜欢

转载自blog.csdn.net/snayf/article/details/81227851