算法导论(Exercise 6.5-9 implement the k-way merge by using heap)

#include<iostream>
#include<vector>
#include<string>
#include<set>
#include<map>
#include<unordered_set>
#include<unordered_map>
#include<algorithm>
#include<xfunctional>
using namespace std;

typedef struct node{
	int index;
	int value;
}node;

typedef struct heap{
	int a_size;
	int h_size;
	node *arr;
}heap;

void Tune(heap &h,int start){
	int i = start;
	node temp = h.arr[start];
	int index = i;
	while (2 * i <= h.h_size){
		int max_temp = temp.value;
		if (h.arr[2 * i].value < max_temp){
			max_temp = h.arr[2 * i].value;
			index = 2 * i;
		}
		if (2 * i + 1 <= h.h_size){
			if (h.arr[2 * i + 1].value < max_temp){
				max_temp = h.arr[2 * i + 1].value;
				index = 2 * i + 1;
			}
		}
		if (index == i){
			break;
		}
		else{
			h.arr[i] = h.arr[index];
			i = index;
		}
	}
	h.arr[index] = temp;
}

void BuildHeap(heap& h){
	for (int i = h.h_size / 2; i > 0; i--){
		Tune(h,i);
	}
}

void Merge_Heap_Sort(heap &h,vector<int> index,vector<vector<int>> arr,vector<int>& result){
	while (h.h_size){
		node temp = h.arr[1];
		result.push_back(temp.value);
		int ind = temp.index;
		if (index[ind] >= arr[ind].size()){
			h.arr[1] = h.arr[h.h_size];
			h.h_size--;
			Tune(h, 1);
		}else{
			temp.value = arr[ind][index[ind]];
			index[ind]++;
			h.arr[1] = temp;
			Tune(h,1);
		}
	}
}

int main(){
	int n;
	cout << "Input the amount of the lists that you want to merge:";
	cin >> n;
	vector<vector<int>> arr(n+1,vector<int>());
	for (int i = 1; i <=n; i++){
		cout << "Input the list size:";
		int t;
		cin >> t;
		for (int j = 0; j < t; j++){
			int a;
			cin >> a;
			arr[i].push_back(a);
		}
	}
	vector<int> index(n+1,0);
	heap h;
	h.a_size = n;
	h.h_size = n;
	h.arr = new node[n+1];
	for (int i = 1; i <= n; i++){
		h.arr[i].index = i;
		h.arr[i].value = arr[i][index[i]];
		index[i]++;
	}
	BuildHeap(h);
	vector<int> result;
	Merge_Heap_Sort(h,index,arr,result);
	cout << "The result:";
	for (int i = 0; i < result.size(); i++){
		cout << result[i] << " ";
	}
	cout << endl;
	system("pause");
	return 0;
}

测试数据:

4

大小     数值

4        1  100 200 300

3        2  600 700

5        3  400 410 420 437

4        4 500 506 507

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值