Swaps and Inversions

题目描述

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.

 

输入

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.

 

输出

For every test case, a single integer representing minimum money to pay.

 

样例输入

3 233 666
1 2 3
3 1 666
3 2 1

 

样例输出

0
3

求逆序对的题目,可以树状数组,可以归并排

#include<bits/stdc++.h>
#include<cstdio>
using namespace std;
typedef long long ll;
ll a[100050],b[100050],cnt;
ll fun(ll l,ll mid,ll r)
{
    if(l!=r)
    {
        cnt=fun(l,(l+mid)/2,mid)+fun(mid+1,(mid+r+1)/2,r);
    }
    else
    {
        return 0;
    }
    ll i=l,j=mid+1;
    for(ll k=l; k<=r; k++)
    {
        if(j>r||(i<=mid&&a[i]<=a[j]))
        {
            b[k]=a[i++];
        }
        else
        {
            b[k]=a[j++],cnt+=mid-i+1;
        }
    }
    for(ll k=l; k<=r; k++)
    {
        a[k]=b[k];
    }
    return cnt;
}
int main()
{
    ll n,ans,x,y;
    while(scanf("%lld%lld%lld",&n,&x,&y)!=EOF)
    {
        memset(b,0,sizeof(b));
        cnt=0;
        for(ll i=1; i<=n; i++)    scanf("%lld",&a[i]);
        ans=fun(1,(1+n)/2,n);
//        cout<<ans<<endl;
        if(x>y)
        {
            printf("%lld\n",(long long)ans*y);
        }
        else
        {
            printf("%lld\n",(long long)ans*x);
        }
    }
    return 0;
}

 

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

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值