Sword refers to the offer series source code-the reverse order in the array

Source: Internet
Author: User

Topic 1348: Reverse order in an array for time limit: 1 seconds Memory limit: 32 Mega Special: No submission: 2133 Resolution: 500 title Description: Two numbers in the array, if the previous number is greater than the following number, then the two numbers form an inverse pair. Enter an array to find the total number of reverse pairs in this array. Input: Each test case consists of two lines: the first row contains an integer n, which represents the number of elements in the array. where 1 <= n <= 10^5. The second row contains n integers, and each array is of type int. Output: Corresponds to each test case, outputting an integer that represents the total number of reverse pairs in the array. Sample input: 47 5 6 4 Sample output: 5

#include <iostream> #include <stdio.h>using namespace std;typedef long Long ll;int N, arr[100010], tmp[100010 ];//merge sort, process statistics in reverse order number ll merge (int start, int mid, int end) {ll cnt = 0;int i = start, j = mid+1, K = Start;while (I<=mid &A mp;& j<= End) {//from large to small sort if (Arr[i] > Arr[j]) {cnt + = (end-j+1);////////The left of the right is reverse order tmp[k++] = arr[i++];} else{tmp[k++] = arr[j++];}} while (i<=mid) tmp[k++] = Arr[i++];while (j<=end) tmp[k++] = arr[j++];for (int i=start; i<=end; i++) arr[i] = Tmp[i] ; return CNT;} ll Inversepairs (int start, int end) {ll cnt = 0;if (Start < end) {int mid = (start + end)/2;cnt + = Inversepairs (Start, mid ); The left half is reversed to the number cnt + = Inversepairs (mid+1, end); Right half cnt + = merge (start, Mid, end); Combine two parts and calculate the quantity}return cnt;}  int main () {while (scanf ("%d", &n)! = EOF) {for (int i=0; i<n; i++) scanf ("%d", &arr[i]); ll ans = inversepairs (0, n-1);p rintf ("%lld\n", ans);} return 0;}

Sword refers to the offer series source code-the reverse order in the array

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.