-
Notifications
You must be signed in to change notification settings - Fork 495
/
Copy pathOptimalMergePattern.cpp
49 lines (43 loc) Β· 1.23 KB
/
OptimalMergePattern.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
//------------Optimal Merge Pattern--------//
#include <bits/stdc++.h>
using namespace std;
// Calculating minimum computations to merge file optimally
int min_computation(int size, int files[]){
int i,total_computation=0;
// creating minheap (insertin files size)
priority_queue<int, vector<int>, greater<int> > pq;
for(i=0;i<size;i++){
pq.push(files[i]);
}
while(pq.size()>1) //merge untill priority queue is not empty
{
int lweight=pq.top();
pq.pop();
int rweight=pq.top();
pq.pop();
int rootweight= lweight + rweight;
total_computation+= rootweight;
pq.push(rootweight);
}
return total_computation;
}
//-----main-------//
/*
files[5]={2,4,7,9,12}
[2,4 merge ->6]
[6,7 merge ->13]
[9,12 merge -> 21]
[13,21 merge -> 34] therefore minimum computation are (6+13+21+34) 74 */
int main()
{
int nfile;
cout<<"Enter the number of files : ";
cin>>nfile; //total files
int *files = new int(nfile);
for(int i=0;i<nfile;i++){
cout<<"Enter the file "<<i+1<<" weight : ";
cin>>files[i];
}
cout<<"Minimum computation required to merge all files in one file are "<<min_computation(nfile,files)<<endl;
return 0;
}