zoukankan      html  css  js  c++  java
  • 归并排序模板

    代码模板

    #include <iostream>
    #include <algorithm>
    
    using namespace std;
    
    const int N = 1e5 + 10;
    
    int n; 
    int a[N], tmp[N];
    
    void merge_sort(int q[], int l, int r)
    {
        if (l >= r) return;
    
        int mid = l + r >> 1;
        merge_sort(q, l, mid);
        merge_sort(q, mid + 1, r);
    
        int k = 0, i = l, j = mid + 1;
        while (i <= mid && j <= r)
            if (q[i] <= q[j]) tmp[k ++ ] = q[i ++ ];
            else tmp[k ++ ] = q[j ++ ];
    
        while (i <= mid) tmp[k ++ ] = q[i ++ ];
        while (j <= r) tmp[k ++ ] = q[j ++ ];
    
        for (i = l, j = 0; i <= r; i ++, j ++ ) q[i] = tmp[j];
    }
    int main()
    {
        cin >> n;
        for (int i = 0; i < n; ++ i) cin >> a[i];
    
        merge_sort(a, 0, n - 1);
    
        for (int i = 0; i < n; ++ i) cout << a[i] << " ";
    
        return 0;
    }
    

    应用1-求逆序对

    原理在于归并排序合并[l,mid]和[mid + 1, r]两个区间时会进行比较,每遇到一对前半段区间小于后半段区间的数就是一组逆序对

    #include <iostream>
    #include <algorithm>
    
    using namespace std;
    
    const int N = 1e5 + 10;
    
    typedef long long LL;
    
    int n;
    int a[N], tmp[N];
    
    LL merge_sort(int a[], int l, int r)
    {
        if (l >= r) return 0;
        
        int mid = l + r >> 1;
        LL res = merge_sort(a, l, mid) + merge_sort(a, mid + 1, r);
        
        int k = 0, i = l, j = mid + 1;
        while (i <= mid && j <= r)
        {
            if (a[i] <= a[j]) tmp[k ++] = a[i ++];
            else 
            {
                res += mid - i + 1; // a[i] > a[j],a[k](k > i) 一定 > a[j],所以这里是i及之后关于a[j]的所有逆序对数量 这里采用res++的问题也是当a[i] > a[j]之后,i后面的数据就看不到a[j]了,后面对应的逆序对自然也就找不到了,这里需要全部加上
                tmp[k ++] = a[j ++];
            }
        }
        
        while (i <= mid) tmp[k ++] = a[i ++];
        while (j <= r) tmp[k ++] = a[j ++];
        
        for (int i = l, j = 0; j < k; ++ i, ++ j) a[i] = tmp[j];
        
        return res;
    }
    int main()
    {
        cin >> n;
        for (int i = 0; i < n; ++ i) cin >> a[i];
        
        cout << merge_sort(a, 0, n - 1) << endl;
        
        return 0;
    }
    
  • 相关阅读:
    std::queue
    关于GridView中如何取得隐藏列的值
    揭秘史上最昂贵的一行Javascript代码
    CentOS 安装 git2.x.x 版本
    error: Some data has already been output, can't send PDF file
    接口和抽象类有什么区别
    php与apache的那些事
    PHP生成PDF完美支持中文,解决TCPDF乱码
    php 表单相关
    快速的去除数组中的指定值
  • 原文地址:https://www.cnblogs.com/G-H-Y/p/14185779.html
Copyright © 2011-2022 走看看