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));
	}
}
发布了22 篇原创文章 · 获赞 19 · 访问量 3550

猜你喜欢

转载自blog.csdn.net/KnightHONG/article/details/81270539