• 整理手套


    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;
    }
    
  • 相关阅读:
    Python面向对象-类成员
    python面向对象-继承
    Linux 静态和动态添加路由
    Linux 添加虚拟网卡
    centos7源码包安装Mongodb,并设置开机自启动
    centos7配置静态ip地址
    Python开发【前端篇】JavaScript和Jquery
    Python爬虫【解析库之pyquery】
    Python爬虫 selenium
    Python爬虫【解析库之beautifulsoup】
  • 原文地址:https://www.cnblogs.com/aziint/p/8416359.html
Copyright © 2020-2023  润新知