2018杭电多校1010: Swaps and Inversions

题目描述

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.

输入

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.

输出

For every test case, a single integer representing minimum money to pay.

样例输入

3 233 666
1 2 3
3 1 666
3 2 1

样例输出

0
3

解题:通过逆序对

#include <iostream>
#include <stdio.h>
#include<cmath>
#define MAXN 100005
using namespace std;
int arge[MAXN];
int temp[MAXN];
long long coun;
void Merge(int head, int mid, int tail)
{
    int pb = head;
    int p1 = head, p2 = mid + 1;
 
    while (p1 <= mid && p2 <= tail)
    {
        if (arge[p1] <= arge[p2])
            temp[pb++] = arge[p1++];
        else
        {
            temp[pb++] = arge[p2++];
            coun += p2 - pb;
        }
    }
    while (p1 <= mid)
        temp[pb++] = arge[p1++];
    while (p2 <= tail)
        temp[pb++] = arge[p2++];
    for (int i = head; i <=tail; i++)
        arge[i] = temp[i];
}
void Merge_Sort(int head, int tail)
{
    if (head < tail)
    {
        int mid = head + (tail - head) / 2;
 
        Merge_Sort(head, mid);
        Merge_Sort(mid + 1, tail);
        Merge(head, mid, tail);
    }
}
int main(void)
{
    int n,x,y;
 
    while (scanf("%d%d%d", &n,&x,&y) != EOF)
    {
        coun = 0;
        for (int i = 0; i < n; i++)
            scanf("%d", &arge[i]);
        Merge_Sort(0, n - 1);
        printf("%lld\n", min(x,y)*coun);
    }
 
    return 0;
}

猜你喜欢

转载自blog.csdn.net/qq_40911499/article/details/81223489