zoukankan      html  css  js  c++  java
  • 归并排序&&树状数组求逆序数

    归并排序:

    #include <iostream>
    #include <vector>
    using namespace std;
    vector<int>input,tmp(500005);
    long long result;
    
    void Merge(int left, int middle, int right)
    {
    int i, j, k;
    i = left, j= middle+1, k = 1;
    while(i<= middle && j <= right)
    {
    if(input[j] < input[i])
    {
    tmp[k++] = input[j++];
    result += middle - i + 1;        
    }
    else
    tmp[k++] = input[i++];
    }
    while(i <= middle)  tmp[k++] = input[i++];
    while(j <= right) tmp[k++] = input[j++];
    
    for(i = left, k = 1; i<= right; i++, k++)
    input[i] = tmp[k];
    }
    
    void MergeSort(int left, int right)
    {
    if(right > left)
    {
    int middle = (right + left) / 2;
    MergeSort(left,middle);
    MergeSort(middle+1,right);
    Merge(left,middle,right);
    }
    }
    
    int main()
    {
    int m,n;
    while(cin>>n)
    {
    if(n==0) break;
    for(int i=0;i<n;i++)
    {
    cin>>m;
    input.push_back(m);
    }
    result = 0;
    MergeSort(0,n-1);
    cout<<result<<endl;
    input.clear();
    }
    }
    树状数组:

    #include <iostream>
    #include <cstring>
    using namespace std;
    
    const int MAXN = 10005;
    int in[MAXN];
    int n;
    
    int LowBit(int t)
    {
    return t&(-t);
    }
    
    int GetSum(int end)
    {
    int sum = 0;
    while(end > 0)
    {
    sum += in[end];
    end -= LowBit(end);
    }
    return sum;
    }
    
    void Plus(int pos, int num)
    {
    while(pos <= n)
    {
    in[pos] += num;
    pos += LowBit(pos);
    }
    }
    
    int main()
    {
    int x,sum;
    while(cin>>n)
    {
    memset(in,0,sizeof(in));
    sum = 0;
    for(int i=1;i<=n;i++)
    {
    cin>>x;
    sum += GetSum(n) - GetSum(x);
    Plus(x,1);
    }
    cout<<sum<<endl;
    }
    }




  • 相关阅读:
    排序算法系列之冒泡排序 (3)
    排序算法系列之选择排序 (2)
    排序算法系列之插入排序 (1)
    深挖 NGUI 基础 之UICamera (二)
    深挖 NGUI 基础 之UIRoot (一)
    JPS寻路和AStar寻路
    旋转矩阵
    [斜边的血条进度]
    UI框架:ui节点控件的绑定方式
    Shader播放序列帧
  • 原文地址:https://www.cnblogs.com/lgh1992314/p/5835044.html
Copyright © 2011-2022 走看看