On the Idea of Dividing and Consolidating

Keywords: C++ iOS

Merge sort

If you want to understand the idea of merging, you can not do without the understanding of merging and sorting. When you look at other people's code, you can't understand it.

Comparing two arrays at a time, notice that it can be two different intervals of an array, and store smaller numbers in a temporary array at a time, thus completing the merge sort. Of course, if these two arrays are ordered, then the question is how to make them ordered, which uses recursion.

    merge_sort(left, mid);
    merge_sort(mid+1, right);

Why do we need to submit it to the next picture?

Example

If the theory is bitter and difficult to understand, here is a question from Luogu, try your hand.
https://www.luogu.org/problem/P1908
Detailed instructions have been marked in code comments

#include<bits/stdc++.h>
using namespace std;
int N;
int a[100000+10], temp[100000+10];
long long ans = 0;          //ans is used to record the number of reverse pairs
void merge_sort(int l, int r)
{
    if(l == r) return ;
    int k = 0 ,mid = (l + r)/2;
    merge_sort(l, mid);             
    merge_sort(mid+1, r);
    //Be careful to recurse first, so that l ~ mid interval and mid + 1 ~ r interval can be sorted from small to large.
    int i = l, j = mid + 1;
    while(i <= mid && j <= r)
    {
        if(a[i] < a[j])
            temp[k++] = a[i++];       //Store smaller numbers in temporary arrays
        else 
        {
            temp[k++] = a[j++];
            ans += mid - i + 1;     //Because a[i]-a[mid] is arranged in incremental order, there are mid-i+1 pairs of inverse pairs before a[j].

        }
    }
    while(i <= mid)         //If a[i...mid] has a surplus
        temp[k++] = a[i++];     
    while(j <= r)           //If a[j...r] has a surplus
        temp[k++] = a[j++];
    for(k = 0; k <= (r - l); k++)
        a[l + k] = temp[k];         //This completes the orderly merging of two intervals.

}
int main()
{
    std::ios::sync_with_stdio(false);
    // freopen("in.txt", "r", stdin);
    // freopen("out.txt", "w", stdout);
    cin >> N;
    memset(a, 0, sizeof(a));
    memset(temp, 0, sizeof(temp));
    for(int i = 0; i < N; i++)
        cin >> a[i];
    merge_sort(0, N-1);
    cout << ans << endl;
}

Reference Blog: https://www.cnblogs.com/mrblug/p/5763138.html

Posted by visualAd on Sun, 06 Oct 2019 15:09:04 -0700