Swaps and Inversions

Swaps and Inversions

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


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 1i<jn 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.
1n,x,y100000, 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
 
Source
 

直接算出逆序对的个数,然后乘于min(x,y);

可以用树状数组求,也可以用归并排序.

 1 #include <bits/stdc++.h>
 2 #define N 100005
 3 #define ll long long int
 4 using namespace std;
 5 struct Node{
 6     int val;
 7     int in;
 8 }node[N];
 9 
10 bool cmp(Node a,Node b){
11     if(a.val==b.val){
12         return a.in<b.in;
13     }
14     return a.val<b.val;
15 }
16 ll sum[N];
17 
18 int lowbit(int x){ return x&(-x); }
19 
20 void update(int x){
21     while(x<=N){
22         sum[x] ++;
23         x += lowbit(x);
24     }
25 }
26 
27 ll query(int x){
28     ll ans = 0;
29     while(x>0){
30         ans += sum[x];
31         x -= lowbit(x);
32     }
33     return ans;
34 }
35 
36 int n,m,k;
37 int main(){
38     while(~scanf("%d%d%d",&n,&m,&k)){
39         memset(node,0,sizeof(node));
40         memset(sum,0,sizeof(sum));
41         for(int i=0;i<n;i++){
42             scanf("%d",&node[i].val);
43             node[i].in = i+1;
44         }
45         sort(node,node+n,cmp);
46         ll ans = 0;
47         for(int i=0;i<n;i++){
48             update(node[i].in);
49             ll k = query(node[i].in-1);
50             ans += (i-k);
51         }
52         ans = ans*min(m,k);
53         printf("%lld\n",ans);
54     }
55     return 0;
56 }

猜你喜欢

转载自www.cnblogs.com/zllwxm123/p/9369123.html