#include<string> #include <vector> #include <fstream> using namespace std; std::vector<int> v; int bigArr[100000]; int helpArr[100000]; _int64 MergeAndCount( int* arr, int left, int mid, int right ) { if( left >= right ) { return 0; } for( int i = left; i <= right; i++ ) { helpArr[i] = arr[i]; } int head1 = left; int head2 = mid + 1; int num = right - left + 1; int k = left; _int64 rNum = 0; for( int i = 0; i < num; i++, k++ ) { if( head1 > mid ) { arr[k] = helpArr[head2++]; } else if( head2 > right ) { arr[k] = helpArr[head1++]; } else if( helpArr[head1] > helpArr[head2] ) { rNum += ( mid - head1 + 1 ); arr[k] = helpArr[head2++]; } else { arr[k] = helpArr[head1++]; } } return rNum; } _int64 GetR( int* arr, int left, int right ) { if( ( right - left ) <= 0 ) { return 0; } int mid = ( left + right ) / 2; _int64 leftNum = GetR( arr, left, mid ); _int64 rightNum = GetR( arr, mid+1, right ); _int64 extraNum = MergeAndCount( arr, left, mid, right ); return leftNum + rightNum + extraNum; } void main() { fstream infile( "IntegerArray.txt" ); string tmp; while( getline( infile, tmp ) ) { int num = atoi( tmp.c_str() ); v.push_back( num ); } for( int i = 0; i < 100000; i++ ) { bigArr[i] = v.at(i); } _int64 rNum = GetR( bigArr, 0, 100000 - 1 ); }
时间: 2024-10-09 21:16:18