整理手套

Description

你现在有 \(N\) 对手套,但是你不小心把它们弄乱了,需要把它们整理一下。 \(N\) 对手套被一字排开,每只手套都有一个颜色,被记为 \(0\)~\(N-1\) ,你打算通过交换把每对手套都排在一起。由于手套比较多,你每次只能交换相邻两个手套。请你计算最少要交换几次才能把手套排整齐。

Solution

可见手套的编号对于解决问题是没有关系的,于是我们对手套重新按出现时间编号。可见答案就是新序列的逆序对数量。
因为存在重复元素,所以采用归并排序来求逆序对。

#include<bits/stdc++.h>
using namespace std;

#define N 400001
#define rep(i, a, b) for (int i = a; i <= b; i++)
#define ll long long

inline int read() {
    int x = 0, flag = 1; char ch = getchar(); while (!isdigit(ch)) { if (!(ch ^ '-')) flag = -1; ch = getchar(); }
    while (isdigit(ch)) x = (x << 1) + (x << 3) + ch - '0', ch = getchar(); return x * flag;
}

int n, a[N], b[N], t[N], tot;
ll ans;

void merge(int l, int r) {
    if(!(l ^ r)) return;
    int m = l + r >> 1; merge(l, m), merge(m + 1, r);
    int p = l, q = m + 1, k = l;
    while(p <= m && q <= r)
        if(a[p] <= a[q]) t[k++] = a[p++];
        else t[k++] = a[q++], ans += q - k;
    while(p <= m) t[k++] = a[p++]; while(q <= r) t[k++] = a[q++];
    rep(i, l, r) a[i] = t[i];
}

int main() {
    n = read() << 1; rep(i, 1, n) if(!b[(a[i] = read())]) b[a[i]] = ++tot; rep(i, 1, n) a[i] = b[a[i]];
    merge(1, n); cout << ans; return 0;
}
posted @ 2018-02-05 10:06  aziint  阅读(422)  评论(0编辑  收藏  举报
Creative Commons License
This work is licensed under a Creative Commons Attribution-NonCommercial 4.0 International License.