HDU 4911 Inversion (merge sort for reverse order)

Source: Internet
Author: User

InversionTime limit:2000/1000 MS (java/others) Memory limit:131072/131072 K (java/others)
Total submission (s): 1898 Accepted Submission (s): 743


Problem Descriptionbobo has a sequence a1,a2,...,. He is allowed to swap adjacentNumbers for no more than k times.

Find the minimum number of inversions after his swaps.

Note:the number of inversions is the number of pair (I,J) where 1≤i<j≤n and Ai>aj.
Inputthe input consists of several tests. For each tests:

The first line contains 2 integers n,k (1≤n≤105,0≤k≤109). The second line contains n integers a1,a2,..., an (0≤ai≤109).
Outputfor each tests:

A single integer denotes the minimum number of inversions.
Sample Input
3 12 2 13 02 2 1

Sample Output
12
#include <iostream> #include <string.h>using namespace std; #define MAX 100010int aux[max];int a[max];int N;    Long long K;long long ans=0;void merge (int a[],int l,int mid,int h) {int i=l;    int j=mid+1;    for (int k=l;k<=h;++k) {aux[k]=a[k];        } for (int k=l;k<=h;k++) {if (i>mid) a[k]=aux[j++];        else if (j>h) a[k]=aux[i++];        else if (Aux[i]<=aux[j]) a[k]=aux[i++];            else {a[k]=aux[j++];        ans+= (mid-i+1);    }}}void mergesort (int a[],int l,int h) {if (h<=l) return;    int mid=l+ (H-L)/2;    MergeSort (A,l,mid);    MergeSort (A,MID+1,H); Merge (a,l,mid,h);}    int main (int argc, char *argv[]) {//freopen ("4911.in", "R", stdin);        while (scanf ("%d%lld", &n,&k)!=eof) {ans=0;        memset (aux,0,sizeof (aux));        for (int k=0;k<n;++k) scanf ("%d", &a[k]);        MergeSort (a,0,n-1);        if (K<ans) printf ("%lld\n", ans-k);    else printf ("0\n"); } rEturn 0;} 

Remember to define ANS and k as Long long


HDU 4911 Inversion (merge sort for reverse order)

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.