POJ_2299 Ultra-QuickSort [merge sort]

Source: Internet
Author: User

Question link: http://poj.org/problem? Id = 2299

Calculate the minimum number of exchanges in the sorting process

This problem is solved using the merge sort grouping algorithm.

Code:

#include <iostream>#include <cstdio>#include <cstring>#define N 500001using namespace std;int a[N];int temp[N];long long ans;void merge(int *a,int start,int mid,int end,int *temp){    int ai=start;    int bi=mid+1;    int k=0;    while (ai<=mid&&bi<=end)    {        if(a[ai]<=a[bi])            temp[k++]=a[ai++];        else        {            temp[k++]=a[bi++];            ans+=(mid-ai+1);        }    }    while (ai<=mid)        temp[k++]=a[ai++];    while (bi<=end)        temp[k++]=a[bi++];    for(int i=0;i<=end-start;i++)    {        a[start+i]=temp[i];    }}void merge_array(int *a,int start,int end){    if(start<end)    {        int mid=(start+end)/2;        merge_array(a,start,mid);        merge_array(a,mid+1,end);        merge(a,start,mid,end,temp);    }}int main(){    int n;    scanf("%d",&n);    while(n)    {        memset(a,0,sizeof(a));        ans=0;        for(int i=0;i<n;i++)            scanf("%d",&a[i]);        merge_array(a,0,n-1);        printf("%I64d\n",ans);        scanf("%d",&n);    }    return 0;}


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.