(133). 33.5 OPTIMAL MERGE PATTERN. - anishsingh90/Data_Structure_And_Algorithm_In_Cpp_github.io GitHub Wiki
#include <bits/stdc++.h> using namespace std; #define int long long
signed main(){ int n; cout << "Enter the number of files: "; cin >> n;
vector<int> a(n);
for(int i=0; i<n; i++){
cin >> a[i];
}
priority_queue<int, vector<int>, greater<int> > minheap;
for(int i=0; i<n; i++){
minheap.push(a[i]);
}
int ans = 0;
while(minheap.size() > 1){
int e1 = minheap.top();
minheap.pop();
int e2 = minheap.top();
minheap.pop();
ans += e1 + e2;
minheap.push(e1 + e2);
}
cout << "Minimum cost: " << ans << endl;
return 0;
}
/* OUTPUT: Enter the number of files: 4 5 2 4 7 Minimum cost: 35 */