decreases inversion count

来源:互联网 发布:手机淘宝差评怎么删 编辑:程序博客网 时间:2024/06/07 07:32
Description


Find a pair in an integer array that swapping them would maximally decrease the inversion count of the array. If such a pair exists, return the new inversion count; otherwise returns the original inversion count.


Definition of Inversion: Let (A[0], A[1] ... A[n]) be a sequence of n numbers. If i < j and A[i] > A[j], then the pair (i, j) is called inversion of A.


Example:
Count(Inversion({3, 1, 2})) = Count({3, 1}, {3, 2}) = 2
InversionCountOfSwap({3, 1, 2})=>
{
  InversionCount({1, 3, 2}) = 1 <-- swapping 1 with 3, decreases inversion count by 1
  InversionCount({2, 1, 3}) = 1 <-- swapping 2 with 3, decreases inversion count by 1
  InversionCount({3, 2, 1}) = 3 <-- swapping 1 with 2 , increases inversion count by 1
}




Input


Input consists of multiple cases, one case per line.Each case consists of a sequence of integers separated by comma.


Output


For each case, print exactly one line with the new inversion count or the original inversion count if it cannot be reduced.




Sample In


3,1,2
1,2,3,4,5


Sample Out


1

0



#include <iostream>#include <assert.h>using namespace std;void swap(int &a,int &b){int temp = a;a = b;b = temp;}//计算反演对的个数int InversionCount(int* arr,int** inversion,const int n){assert(!(arr==NULL));assert(!(inversion==NULL));assert(n>0);int count = 0;for(int i=0;i<n-1;i++){for(int j=i+1;j<n;j++){if(arr[i] > arr[j]){inversion[0][count] = i;inversion[1][count] = j;count++;}}}return count;}//计算交换反演对之后的countint InversionCountOfSwap(int* arr,int** inversion,const int count,const int n){assert(!(arr==NULL));assert(!(inversion==NULL));assert(count>0);int min = 1000;for(int i=0;i<count;i++){swap(arr[inversion[0][i]],arr[inversion[1][i]]);if(min>InversionCount(arr,inversion,n))min = InversionCount(arr,inversion,n);}return min;}void print(int *arr,int n){for(int i=0;i<n;i++){cout<<arr[i];}cout<<endl;}int _tmain(int argc, _TCHAR* argv[]){int *arr = new int[100000];if(!arr) exit(OVERFLOW);int **inversion;inversion = (int **)malloc(2*sizeof(int*));for(int i=0;i<2;i++){inversion[i] = (int *)malloc(100000*sizeof(int));}if(!inversion) exit(OVERFLOW);int flag = 1;while(flag>=1){int i = 0;while(1){cin>>arr[i];if(arr[i]<=0)break;i++;}int n = i;//记住数组大小//print(arr,n);int count = InversionCount(arr,inversion,n);cout<<count<<endl;if(count>0){cout<<InversionCountOfSwap(arr,inversion,count,n)<<endl;}elsecout<<count<<endl;//判断是否继续循环cin>>flag;}delete[] arr;arr = NULL;delete[] *inversion;*inversion = NULL;delete[] inversion;inversion = NULL;return 0;}


0 0