Swaps and Inversions

本文介绍了一种利用归并排序算法高效计算整数序列中逆序对数量的方法,并通过实例演示如何求解最小花费问题。通过对序列进行递归划分与合并,实现了O(nlogn)的时间复杂度。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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;
    }
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值