Poj-2299 [calculate the number of reverse orders by means of Merge Sorting]

Source: Internet
Author: User
For details about Merge Sorting, see "Introduction to algorithms"-Divide and conquer law. In the following example, we use the merge method to calculate the number of reverse orders for the 2299 questions in poj:
/** The question indicates the number of exchanges that require Bubble sorting. Algorithm used: sort by merge to calculate the number of reverse orders. # This question fully demonstrates that even if merge itself may not use much, the idea of separation and metallurgy is omnipresent. **/# include <stdio. h> int left [250003], right [250003]; long count; void Merge (int * a, int P, int Q, int R) {int I, j, k, N1, N2; n1 = Q-p + 1; N2 = r-Q; for (I = 0; I <N1; I ++) {left [I] = A [p + I] ;}for (I = 0; I <N2; I ++) {right [I] = A [q + I + 1];} left [N1] = right [n2] = 0x7fffffff; I = J = 0; For (k = P; k <= r; k ++) {If (left [I] <= right [J]) {A [k] = left [I]; I ++ ;} else {A [k] = right [J]; j ++; count + = n1-i;/** this step is added in the merge sort, used to count the number of reverse orders **/} return;} void mergesort (int * a, int P, int R) {int Q; If (P <R) {q = (p + r)/2; mergesort (A, p, q); mergesort (A, q + 1, R); merge (A, p, q, r);} return;} int main () {int N, I, a [500001]; while (scanf ("% d", & N) {COUNT = 0; for (I = 0; I <n; I ++) {scanf ("% d", & A [I]) ;} mergesort (, 0, n-1); printf ("% LLD/N", count );}}

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.