HDU 6318 Swaps and Inversions(归并排序/树状数组)

Swaps and Inversions

Time Limit: 2000/1000 MS (Java/Others)    Memory Limit: 32768/32768 K (Java/Others)
Total Submission(s): 637    Accepted Submission(s): 254


 

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,求把序列变成顺序序列至少消耗多少费用。

思路:就是求逆序数啊,因为两种方法都是交换一次少一个逆序数,最终成为顺序序列,因此只需要求出逆序数然后乘上xy中小的那个。用归并排序或树状数组都行,不过树状数组需要离散化,我用的归并排序。

代码:(我直接套模板。。。)

#include<bits/stdc++.h>
#define ll long long
#define inf 0x3f3f3f3f
using namespace std;
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;
}

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值