Swaps and Inversions
Time Limit: 2000/1000 MS (Java/Others) Memory Limit: 32768/32768 K (Java/Others)
Total Submission(s): 0 Accepted Submission(s): 0
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 元的操作:相邻交换的次数 * y。求最小花费。
解题思路:逆序对 * min(x,y)。
AC 代码
#include<bits/stdc++.h> #include<cmath> #define mem(a,b) memset(a,b,sizeof a); #define INF 0x3f3f3f3f using namespace std; typedef long long ll; const int maxn=100005; int a[maxn],b[maxn]; ll cnt; void Merge(int start,int mid,int end) { int i=start,j=mid+1,k=start; while(i<=mid && j<=end){ // 因为 end=n-1,所以可以取到 if(a[i]<=a[j]) b[k++]=a[i++]; // 是否需要等号取决于,比如:4 2 2 1 中的 2 2 是否算一对 else{ // 当a[i]>a[j]的时候,如果此时把a[j]放在a[i]前面,那么a[i]到a[mid]的值都大于a[j],因此在交换之前属于逆序对 // 左边数组 9 8 7 右边数组 1 2 3 // 当把 1 放在 9 前面,那么9 8 7 都是 1 的逆序对,数量 j-k cnt+=j-k; b[k++]=a[j++]; } } while(j<=end) b[k++]=a[j++]; while(i<=mid) b[k++]=a[i++]; for(i=start;i<=end;i++) a[i]=b[i]; } void MergeSort(int start,int end) { if(start<end){ int mid=start+((end-start)>>1); MergeSort(start,mid); MergeSort(mid+1,end); Merge(start,mid,end); } } int main() { int n,x,y; while(~scanf("%d%d%d",&n,&x,&y)){ cnt=0; for(int i=0;i<n;i++){ scanf("%d",&a[i]); } MergeSort(0,n-1); printf("%lld\n",min(x,y)*cnt); } return 0; }