POJ 2299 ultra-quicksort (merge sort, reverse order number)

Source: Internet
Author: User

Links: Poj 2299

Test Instructions : gives a sequence of length n, which can only exchange two adjacent elements at a time.

Ask at least a few times to make the sequence an ascending sequence

Analysis : Bubble sort can only swap adjacent two elements at a time. That is to ask

use bubble sort to make it the number of interchanges of an ascending sequence, every time I exchange a record.

However, this data is larger, the bubble sort efficiency is low, will time out

In this case, we can use the merge sort to find the inverse number of the sequence by using the merge sort .

and the number of reverse order of a sequence = Only allow two adjacent elements to exchange, to get an ordered sequence of the number of exchanges

#include <stdio.h> #include <stdlib.h> #define M 500000int a[m+5],l[m+5],r[m+5];__int64 t;void cmp (int ll, int Mid,int rr) {    int m=0,n=0,i,j,k;    for (i=ll;i<=mid;i++)        l[m++]=a[i];    for (i=mid+1;i<=rr;i++)        r[n++]=a[i];    i=j=0;    K=ll;    while (i<m&&j<n) {        if (L[i]<=r[j])            a[k++]=l[i++];        else{            a[k++]=r[j++];            T+=m-i;   Calculates the number of reverse order        }    }    while (i<m)        a[k++]=l[i++];    while (j<n)        a[k++]=r[j++];} void MergeSort (int l,int r) {    int mid;    if (l<r) {        mid= (l+r)/2;        MergeSort (l,mid);        MergeSort (mid+1,r);        CMP (L,MID,R);}    } int main () {    int n,i;    while (scanf ("%d", &n) &&n) {        for (i=0;i<n;i++)            scanf ("%d", &a[i]);        t=0;        MergeSort (0,n-1);        printf ("%i64d\n", t);    }    return 0;}

Poj 2299 ultra-quicksort (merge sort, reverse number)

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.