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

Swaps and Inversions

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

 

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

题目大意:

有一串长度为n的数字,现在给出x和y,这一串数字里每存在一个逆序数(例如样例2:3 2 1,3的逆序数是0,2的逆序数是1,1的逆序数是2),就要付出x元的代价,当然你也可以交换相邻的两个数字来减少逆序数,每交换一次需要支付y元。

解法:

科普:逆序数的意思是一串数字中,当前数字的前面有多少个比它大的数字,总的逆序数就是全部数字逆序数的总和。

其实写多几组数据就会发现每交换两个数字(前大后小),逆序数就会相应的减少1,所以我们可以推出,逆序数=交换次数,其实线性代数学好了,这题还是很容易理解的。

所以我们只需要求出逆序数,判断x和y的大小,求逆序数只需要套用归并排序模板就可以愉快的AC了,附上代码:

#include <bits/stdc++.h>
#define ll long long
#define MAXN 100005
using namespace std;

ll a[MAXN],tep[MAXN];// a为原数组,tep为临时数组

ll merge(ll low,ll mid,ll high){
	ll i=low,j=mid+1,k=low;
	ll count=0;
	while(i<=mid&&j<=high){
		if(a[i]<=a[j])
			tep[k++]=a[i++];
		else{
			tep[k++]=a[j++];
			count+=j-k;// 每当后段的数组元素提前时,记录提前的距离
		}
	}
	while(i<=mid)
		tep[k++]=a[i++];
	while(j<=high)
		tep[k++]=a[j++];
	for(i=low;i<=high;i++)// 写回原数组
		a[i]=tep[i];
	return count;
}

ll mergeSort(ll a,ll b){
	if(a<b){
		ll mid=(a+b)/2;
		ll count=0;
		count+=mergeSort(a,mid);
		count+=mergeSort(mid+1,b);
		count+=merge(a,mid,b);
		return count;
	}
	return 0;
}

int main(){
	long long x,y,n;
	while(scanf("%lld%lld%lld",&n,&x,&y)!=EOF){
		for(ll i=0;i<n;i++)
			scanf("%lld",&a[i]);
		printf("%lld\n",mergeSort(0,n-1)*min(x,y));
	}
}

 

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

KnightHONG

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值