-
Notifications
You must be signed in to change notification settings - Fork 0
/
merge.cpp
73 lines (58 loc) · 1.8 KB
/
merge.cpp
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
#include <vector>
#include <iostream>
#include <fstream>
#include <cstdlib>
#include <ctime>
#include <cstring>
#include <queue>
void printUsage(char* name) {
std::cout << "usage: " << name << " -o output_file -f input_file ..." << std::endl;
}
struct Seq {
int value;
std::ifstream source;
Seq(char* filename) : source(filename) {}
};
bool next(Seq* seq) {
if (seq->source.good()) {
seq->source >> seq->value;
return true;
}
return false;
}
void merge(std::vector<Seq*>& sequences, std::ofstream& output) {
/* Greater<Seq*> comparator for Seq* to create min heap */
auto comp = []( const Seq* lhs, const Seq* rhs ) { return lhs->value > rhs->value; };
std::priority_queue<Seq*, std::vector<Seq*>, decltype(comp)> pq(sequences.begin(), sequences.end(), comp);
while(!pq.empty()) {
/* Get and pop minimum element */
Seq* top = pq.top();
pq.pop();
output << top->value << '\n';
/* Since the minimum element is a sequence, if it has a next value,
we can re-insert into the heap for the next iteration */
if(next(top)) {
pq.push(top);
}
}
}
int main(int argc, char *argv[]) {
/* Must provide -o and -f */
if (argc < 5 || strncmp(argv[1], "-o", 3) != 0 || strncmp(argv[3], "-f", 3) != 0) {
printUsage(argv[0]);
return 1;
}
char* outputFilename = argv[2];
std::ofstream output(outputFilename);
std::vector<Seq*> sequences = std::vector<Seq*>();
for (int i = 4; i < argc; i++) {
char* inputFilename = argv[i];
Seq* seq = new Seq(inputFilename);
if(next(seq)) {
sequences.push_back(seq);
}
}
merge(sequences, output);
output.close();
return 0;
}