|
| 1 | +#include<iostream> |
| 2 | +#include<string> |
| 3 | +#include<vector> |
| 4 | +#include<math.h> |
| 5 | +#include <bits/stdc++.h> |
| 6 | +#define ll long long |
| 7 | + |
| 8 | +using namespace std; |
| 9 | +vector<ll> level[10000]; |
| 10 | +void print(vector<vector<ll> > p,ll i,ll j,ll* a,ll l) //print function |
| 11 | +{ |
| 12 | + if(i>j) return ; |
| 13 | + |
| 14 | + print(p,i,p[i][j]-1,a,l+1); //recursion go to left side |
| 15 | + level[l].push_back(a[p[i][j]]); |
| 16 | + print(p,p[i][j]+1,j,a,l+1); //recursion go to right side |
| 17 | +} |
| 18 | + |
| 19 | +int main() |
| 20 | +{ |
| 21 | + ll n; |
| 22 | + cin >>n; |
| 23 | + pair<ll,ll> a[n]; |
| 24 | + ll b[n]; |
| 25 | + for(ll i=0; i<n; i++) |
| 26 | + { |
| 27 | + cin >> a[i].first >>a[i].second; |
| 28 | + } |
| 29 | + sort(a,a+n); |
| 30 | + for(ll i=0; i<n; i++) |
| 31 | + { |
| 32 | + b[i]=a[i].first; |
| 33 | + } |
| 34 | + ll sum[n+1]; |
| 35 | + sum[0]=0; |
| 36 | + for(ll i=0; i<n; i++) |
| 37 | + { |
| 38 | + sum[i+1]=sum[i]+a[i].second; //pre-calculating sum of cost instead of calling sum() again and again |
| 39 | + } |
| 40 | + ll dp[n][n]; |
| 41 | + |
| 42 | + vector<vector<ll> > p; |
| 43 | + |
| 44 | + for(ll i=0; i<n; i++) //initialize all values of dp array to zero |
| 45 | + { |
| 46 | + vector<ll> t; |
| 47 | + for(ll j=0; j<n; j++) |
| 48 | + { |
| 49 | + dp[i][j]=0; |
| 50 | + t.push_back(-1); |
| 51 | + } |
| 52 | + p.push_back(t); |
| 53 | + } |
| 54 | + |
| 55 | + for(ll k=0; k<n; k++) |
| 56 | + { |
| 57 | + ll i=0; |
| 58 | + for(ll j=k; j<n; j++) |
| 59 | + { |
| 60 | + ll min=LONG_LONG_MAX; |
| 61 | + for(ll m=j; m>=i; m--) |
| 62 | + { |
| 63 | + ll temp1=0,temp2=0; |
| 64 | + if(i<m) temp1=dp[i][m-1]; |
| 65 | + if(m<j) temp2=dp[m+1][j]; |
| 66 | + |
| 67 | + ll temp=temp1 + temp2 + (sum[j+1]-sum[i]); //taking all possibilities for minimum cost |
| 68 | + if(min>=temp) |
| 69 | + { |
| 70 | + min=temp; |
| 71 | + p[i][j]=m; |
| 72 | + } |
| 73 | + } |
| 74 | + dp[i][j]=min; //dp value set as minimum value |
| 75 | + i++; |
| 76 | + } |
| 77 | + } |
| 78 | + cout<<"Minimum Cost : "<<dp[0][n-1]<<endl<<endl; //at dp[0][n-1] total minimum cost stored |
| 79 | + |
| 80 | + cout<<"Optimal BST with minimum cost as under : "<<endl<<endl; |
| 81 | + |
| 82 | + print(p,0,n-1,b,0); //print function |
| 83 | + ll i=0; |
| 84 | + while(level[i].size()) //printing level of BST |
| 85 | + { |
| 86 | + cout<< "Level "<<i+1<<": "; |
| 87 | + for (std::vector<ll>::const_iterator j = level[i].begin(); j != level[i].end(); ++j) |
| 88 | + { |
| 89 | + std::cout << *j <<" "; |
| 90 | + } |
| 91 | + cout<<endl; |
| 92 | + i++; |
| 93 | + } |
| 94 | + return 0; |
| 95 | +} |
0 commit comments