-
Notifications
You must be signed in to change notification settings - Fork 368
/
Optimal_Merge_pattern.py
53 lines (43 loc) · 1.69 KB
/
Optimal_Merge_pattern.py
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
# ====================== Problem Statement ==========================
'''
Given n number of sorted files, the task is to find the minimum computations done to reach the Optimal Merge Pattern.
When two or more sorted files are to be merged altogether to form a single file, the minimum computations are done to reach this file are known as Optimal Merge Pattern
For example
Q If there are 5 files apply optimal merge pattern.(20,30,10,5,30).
Ans
Step 1: Sort files in ascending order of their sizes.
x4 x3 x1 x2 x5
5 10 20 30 50
Step 2: Pick the files of smaller size and merge them
Merge x3 and x4 |z1|=5+10=15
Merge z1 and x1|z2|=35
Merge x2 and x5|z3|=60
Merge z3 and z2=60+35=95
Total no of moves= 205
205 is the minimum no of moves if we combine in different ways then moves will be greater than 205.
Approach
1)Sort files in ascending order of sizes.
2)Pick the files of smaller sizes and merge them.
'''
#====================== Code with Python ==========================
from heapq import heapify, heappush, heappop
# Creating empty heap
heap = []
heapify(heap)
#function for finding min no of moves
def minmoves(size,lst):
# Adding items to the heap using heappush function
for i in range(0,size):
heappush(heap, lst[i])
count=0
while(len(heap)>1):
temp=heappop(heap)
temp1=heappop(heap)
count+=temp+temp1
heappush(heap,temp+temp1)
return count
size=int(input("Enter no of files : "))
print("Enter the sizes of files : ")
files=list(map(int,input().split()))
files.sort()
print("Minimum no of moves : "+str(minmoves(size,files)))