hdu6318 离散化+线段树求逆序数

Swaps and Inversions

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


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 [10^9,10^9]. 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交换序列中的任意相邻的一对数,使序列符合要求(本题从小到大)
 
 
代码:
#include <stdio.h>    
#include <iostream>    
#include <queue>
#include <vector>
#include <algorithm>
#include <string.h>
#define fio ios::sync_with_stdio(false);cin.tie(0);cout.tie(0)
#define ll long long
#define maxx 100009
using namespace std;

int n, a[maxx], c[maxx];
int x, y;

struct node
{
    int v;
    int order;
}in[maxx];

int lowbit(int x) {
    return x & (-x);
}

void updata(int x, int val) {
    for (int i = x; i <= n; i += lowbit(i)) {
        c[i] += val;
    }
}
int getsum(int end) {
    int sum = 0;
    for (int i = end; i > 0; i -= lowbit(i))
    {
        sum += c[i];
    }
    return sum;
}

bool cmp(const node &a, const node &b) {
    if (a.v != b.v) return a.v < b.v;
    return a.order < b.order;
}//这个地方必须排order

int main() {
    fio;
    while (cin>>n>>x>>y)
    {
        memset(c, 0, sizeof c);
        memset(a, 0, sizeof a);
        memset(in, 0, sizeof in);

        for (int i = 1; i <= n; i++)
        {
            cin >> in[i].v;
            in[i].order = i;
        }

        sort(in + 1, in + n + 1, cmp);
        for (int i = 1; i <= n; i++) {
            a[in[i].order] = i;
        }

        ll sum = 0,ans;
        for (int i = 1; i <= n; i++) {
            updata(a[i], 1);
            sum += i - getsum(a[i]);
        }
        ans = sum * min(x, y);
        cout << ans << endl;
    }
    //getchar();
    return 0;
}

猜你喜欢

转载自www.cnblogs.com/the-way-of-cas/p/9380748.html
今日推荐