"Divide and conquer" in array A, returns the number of I<j, and A[i]>a[j] (I,J) pairs

Source: Internet
Author: User

Title: EPI


In the subject, divide the array into the left and right parts, calculate the number of invrted pair of the left and right two parts respectively, then calculate a[i] and a[j] on one side of the case, then add the three.

int Count_invert_core (vector<int> &arr,int begin,int end) {if (End-begin + 1 < 2) return 0;if (End-begin + 1 = = 2) {if (Arr[begin] > Arr[end]) return 1;elsereturn 0;} At least 3 number int mid = begin + (end-begin) >>1;int num1 = Count_invert_core (arr, begin, mid); int num2 = Count_invert_cor  E (arr, mid + 1, end), sort (arr.begin () + Begin, Arr.begin () + mid + 1), sort (arr.begin () + mid+1, Arr.begin () + end + 1); int Add = 0;//add represents a number in the first half, a number of invrted pair in the second half for the (int i1 = begin, I2 = mid + 1; i1 <= mid; i1++) {while (i2<=end && Arr[i1] > Arr[i2]) i2++;if (i2 <= end) Add + = i2-1-Mid-1 + 1;elseadd + = end-mid-1 + 1;} return NUM1 + num2 + add;} int Count_invert (vector<int> &arr) {return Count_invert_core (Arr,0,arr.size ()-1);}


"Divide and conquer" in array A, returns the number of I<j, and A[i]>a[j] (I,J) pairs

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.