Merge Sorting in the fifth case of multiple schools

Source: Internet
Author: User

HDU 4911 Inversion

Test site: Merge and sort

Idea: I forgot to know that I could use the merge sort to calculate the number of reverse orders during the competition, but I forgot the essence of the merge sort and would not do it ......

When we can see that two adjacent numbers can be exchanged, it seems that the merging and sorting are not adjacent, and then we will be dizzy ...... After reading it again, we found that merging is an adjacent exchange, which is used to calculate the number of reverse orders ...... This merge sort competition is coming ...... Great!

#include<iostream>#include<cstdio>#include<cstring>#include<algorithm>#include<map>#include<queue>#include<set>#include<cmath>#include<limits>#include<bitset>#define mem(a,b) memset(a,b,sizeof(a))#define lson i<<1,l,mid#define rson i<<1|1,mid+1,r#define INF 510010#define maxn 100010using namespace std;typedef long long ll;typedef unsigned long long ull;ll sum;void merge(ll A[], int p, int q, int r){    int n1 = q - p + 1;    int n2 = r - q;    ll *L=new ll[n1 + 1];    ll *R=new ll[n2 + 1];    for(int i = 0; i < n1; i++)        L[i] = A[p + i];    for(int i = 0; i < n2; i++)        R[i] = A[q + 1 + i];    L[n1] = numeric_limits<ll>::max();    R[n2] = numeric_limits<ll>::max();    int i = 0, j = 0;    for(int k = p; k <= r; k++)    {        if(L[i] <= R[j]) A[k] = L[i],i++;        else A[k] = R[j],j++,sum += n1 - i;    }    delete []L;    delete []R;}void mergesort(ll A[], int l, int r){    if(l >= r)        return ;    int q = (l + r) / 2;    mergesort(A, l, q);    mergesort(A, q + 1, r);    merge(A, l, q, r);}ll a[100005];int main(){    //freopen("test.txt","r",stdin);    int n,k,i;    while(~scanf("%d%d",&n,&k))    {        sum=0;        for(i=0; i<n; i++)            scanf("%d",a+i);        mergesort(a,0,n-1);        if(sum>k) printf("%I64d\n",sum-k);        else puts("0");    }    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.