栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > C/C++/C#

逆序对计数问题

C/C++/C# 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

逆序对计数问题

#include 
#include 
#include 
#include 
#include 
using namespace std;

int nums[] = { 13,8,10,6,15,18,};//12,20,9,14,17,19 

bool randNums(int n) {
	fstream ofs("data.txt", ios::out | ios::trunc);
	if (!ofs.is_open()) {
		cout << "文件打开失败!" << endl;
		return false;
	}
	ofs << n << ' ';
	int temp = 0;
	for (int i = 0; i < n; i++) {
		temp = rand() % 200;  //随机数在0到200
		ofs << temp << ' ';
	}
	return true;
}

//归并排序
int mergeCount(int nums[],int left,int mid,int right) 
{
	vector nums_0;
	int k = 0, j = left, sum = 0;

	for(int i=mid;i<=right;i++)
	{
		while (nums[j] < nums[i] && j < mid)
		{
			nums_0.push_back(nums[j++]);
		}
		nums_0.push_back(nums[i]);
		sum += mid - j;
	}

	while (j < mid) 
	{
		nums_0.push_back(nums[j++]);
	}

	for (vector::iterator it = nums_0.begin(); it != nums_0.end(); it++) {
		nums[left++] = *it;
	}

	return sum;
}

int countInver(int nums[],int left,int right)
{
	if (left >= right)
	{
		return 0;
	}
	int mid = floor((left + right) / 2);
	int S1 = countInver(nums, left, mid);
	int S2 = countInver(nums, mid + 1, right);
	int S3 = mergeCount(nums, left, mid + 1, right);
	return S1 + S2 + S3;
}

int* readNums() {
	fstream ifs("data.txt", ios::in);
	int n;
	ifs >> n;
	int i = 0;
	int* nums = new int[n];
	
	while (ifs >> n) {
		//cout << n << ' ';
		nums[i++] = n;
	}
	cout << endl;
	cout << endl;
	return nums;
}

int main() 
{
	int n = 10000;  //次数修改  次数太大 (int)sum溢出 
	srand((unsigned int)time(NULL));
	if (!randNums(n)) {
		return 0;
	}
	int* nums = readNums();

	cout << endl;
	clock_t sTime, eTime;
	sTime = clock();
	ULonGLONG startTime = GetTickCount64();

	cout << countInver(nums, 0, n-1) << endl;


	ULonGLONG endTime = GetTickCount64();
	eTime = clock();
	cout << "THe run time is:" << endTime - startTime << "ms" << endl;
	cout << "THe run time is:" << ((double)eTime - sTime) / CLOCKS_PER_SEC << "s" << endl;

	return 0;
}

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/289505.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号