-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathKWay_Merge.cpp
More file actions
93 lines (83 loc) · 1.65 KB
/
KWay_Merge.cpp
File metadata and controls
93 lines (83 loc) · 1.65 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
//second method not well tested
#include "stdafx.h"
#include "iostream"
#include "vector"
#include "string"
#include "map"
#include <algorithm>
#include <stdlib.h>
#include <time.h>
#include <stack>
#include <sstream>
#include <iomanip>
#include <random>
#include <assert.h>
#include <iterator>
#include <queue>
using namespace std;
struct Node{
int data;
int index;
Node(int _data, int _index):data(_data), index(_index){}
};
struct MyCompare{
bool operator()(const Node& n1, const Node& n2)
{
return n1.data>n2.data;
}
};
vector<int> kWayMerge(vector<vector<int> > num)
{
priority_queue<Node, vector<Node>, MyCompare> q;
int n=num.size();
vector<int> index(n, 0);
vector<int> result;
while(true)
{
if(q.empty())
{
for(int i=0;i<n;i++)
{
if(index[i]<num[i].size())
{
Node tmp(num[i][index[i]], i);
q.push(tmp);
index[i]++;
}
}
}
if(q.empty())break;
Node front=q.top();
q.pop();
result.push_back(front.data);
if(index[front.index]<num[front.index].size())
{
Node tmp(num[front.index][index[front.index]], front.index);
index[front.index]++;
q.push(tmp);
}
}
return result;
}
void testKWayMerge(int n)
{
vector<vector<int> > nums;
srand(time(NULL));
for(int i=0;i<n;i++)
{
vector<int> tmp;
for(int j=0;j<i;j++)
{
if(j==0)tmp.push_back(rand()%50);
else tmp.push_back(tmp[j-1]+rand()%50);
}
nums.push_back(tmp);
}
vector<int> result= kWayMerge(nums);
for(int i=0;i<result.size();i++)cout<<result[i]<<" ";
}
int _tmain(int argc, _TCHAR* argv[])
{
testKWayMerge(10);
return 0;
}