zoukankan      html  css  js  c++  java
  • 逆序对

    #include<iostream>
    #include<algorithm>
    #include<string>
    using namespace std;
    void print(int a[],int n)
    {
        for(int i=0;i<n;i++) cout << a[i] << '	';
        cout << endl;
    }
    void  mergeSort(int a[],int b[],int L,int R,int &ans)
    {
        if(L==R) return ;
        int mid = (L+R)/2;
        mergeSort(a,b,L,mid,ans);
        mergeSort(a,b,mid+1,R,ans);
        int k=L,i=L,j=mid+1;
        while(i<=mid && j<=R)
        {
            if(a[i]<a[j]) b[k++]=a[i++];
            else 
            {
                b[k++]=a[j++];
                ans += mid-i+1; //逆序对 
            }
        } 
        while(i<=mid) b[k++]=a[i++];
        while(j<=R) b[k++]=a[j++];
        for(i=L;i<=R;i++) a[i]=b[i];
    }
    int main(void)
    {
        freopen("D:\1.txt","r",stdin);
        int n,a[100],b[100],ans=0;
        cin >> n;
        for(int i=0;i<n;i++) cin >> a[i];
        print(a,n);
        mergeSort(a,b,0,n-1,ans);
        print(a,n);
        cout << "ans=" << ans; 
        return 0;    
    }
  • 相关阅读:
    7-25 念数字
    7-24 约分最简分式
    7-23 币值转换
    HDU-1102-Constructing Roads
    HDU-1301-Jungle Roads
    链式向前星
    HDU-1217-Arbitrage(SPFA)
    POJ-1258-Agri-Net
    HDU-1863-畅通工程
    POJ-3050-Hoscotch
  • 原文地址:https://www.cnblogs.com/zuimeiyujianni/p/10461591.html
Copyright © 2011-2022 走看看