Skip to content

Commit 229b984

Browse files
author
Sahil
authored
Merge pull request royalpranjal#28 from khannagautam/patch-1
Adding solution for Ways to form Max Heap
2 parents 4630434 + 540e4f1 commit 229b984

File tree

1 file changed

+47
-0
lines changed

1 file changed

+47
-0
lines changed

Heaps-and-Maps/WaysToFormMaxHeap.cpp

Lines changed: 47 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,47 @@
1+
long long dp[105];
2+
long long comb[105][105];
3+
#define MOD 1000000007
4+
int rec(int n)
5+
{
6+
if(n<=1)
7+
return 1;
8+
if(dp[n] != -1)
9+
return dp[n];
10+
int i;
11+
int fill = 0;
12+
int pw = 2;
13+
int left,right;
14+
left = right = 0;
15+
16+
while(fill+pw < n-1)
17+
{
18+
fill += pw;
19+
left += pw/2;
20+
right += pw/2;
21+
pw *= 2;
22+
}
23+
int rem = n-1-fill;
24+
if(rem > pw/2)
25+
{
26+
left += pw/2;
27+
right += (rem-pw/2);
28+
}
29+
else
30+
left += rem;
31+
32+
return dp[n] = (((rec(left)*1LL*rec(right))%MOD)*1LL*comb[n-1][left])%MOD;
33+
}
34+
int Solution::solve(int A)
35+
{
36+
int i,j;
37+
for(i=0;i<=100;i++)
38+
dp[i] = -1;
39+
comb[0][0] = 1;
40+
for(i=1;i<=100;i++)
41+
{
42+
comb[i][0] = comb[i][i] = 1;
43+
for(j=1;j<i;j++)
44+
comb[i][j] = (comb[i-1][j-1]+comb[i-1][j])%MOD;
45+
}
46+
return rec(A);
47+
}

0 commit comments

Comments
 (0)