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;}