码迷,mamicode.com
首页 > 其他好文 > 详细

Algorithms: Design and Analysis, Part 1 【program 1/逆序数】

时间:2015-10-24 11:18:25      阅读:132      评论:0      收藏:0      [点我收藏+]

标签:

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

 

Algorithms: Design and Analysis, Part 1 【program 1/逆序数】

标签:

原文地址:http://www.cnblogs.com/yxfu/p/4906330.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!