zoukankan      html  css  js  c++  java
  • 分治算法——正规归并排序中顺便计算出数组中的逆序对数

    C++版本代码如下

    #include <iostream>
    #include <math.h>
    #include <cstring>
    using namespace std;
    
    #define MAXSIZE 256
    
    int num = 0; // 全局变量或者成员变量
    
    void merge(int a[], int low, int middle, int high) {
        int i = low, j = middle + 1, k = 0;
        int tmp[high - low + 1];
        while (i<=middle && j<=high) {
            if (a[i] <= a[j])
                tmp[k++] = a[i++];
            else{
                // 统计i与middle之间,比a[j]大的元素个数
                num += (middle - i + 1);
                tmp[k++] = a[j++];
            }
        }
    
        // 处理剩下的
        while (i <= middle)
            tmp[k++] = a[i++];
    
        while (j <= high)
            tmp[k++] = a[j++];
    
        // 从tmp拷贝回a
        for (i = 0; i < high - low + 1; ++i) {
            a[low + i] = tmp[i];
        }
    }
    
    void mergeSortCounting(int a[], int low, int high) {
        if (low >= high) return;
        int middle = low + ((high - low)>>1);
        mergeSortCounting(a, low, middle);
        mergeSortCounting(a, middle+1, high);
        merge(a, low, middle, high);
    }
    
    int main(int argc, char* argv[]){
        int arr[6] = {1,5,6,2,3,4};
        mergeSortCounting(arr, 0, 5);
        for(int i = 0; i < 6; i++){
            cout<<arr[i]<<"	";
        }
        cout<<endl<<num;
        return 0;
    }
    
  • 相关阅读:
    BZOJ 4318: OSU!
    BZOJ 3450: Tyvj1952 Easy
    BZOJ 1426: 收集邮票
    BZOJ 1415: [Noi2005]聪聪和可可
    BZOJ 1778: [Usaco2010 Hol]Dotp 驱逐猪猡
    BZOJ 3270: 博物馆
    BZOJ 3143: [Hnoi2013]游走
    BZOJ 3166: [Heoi2013]Alo
    BZOJ 3261: 最大异或和
    BZOJ 1022: [SHOI2008]小约翰的游戏John
  • 原文地址:https://www.cnblogs.com/flyingrun/p/13475861.html
Copyright © 2011-2022 走看看