FAILING for large cases ...plzz help


#1

void order(int l1,int l2,int i,int j,vector&ans,vector<vector>&dp,vector&B){
if(j<i){return ;}
if(i==j){
ans.push_back(B[i]);
return ;
}
unsigned long long int l=l2-l1;
if(l+dp[i+1][j]==dp[i][j]){
ans.push_back(B[i]);
order(B[i],l2,i+1,j,ans,dp,B);
return ;
}
for(int k=i+1;k<j;k++){
if(l+dp[i][k-1]+dp[k+1][j]==dp[i][j]){
ans.push_back(B[k]);
order(l1,B[k],i,k-1,ans,dp,B);
order(B[k],l2,k+1,j,ans,dp,B);
return ;
}
}
if(l+dp[i][j-1]==dp[i][j]){
ans.push_back(B[j]);
order(l1,B[j],i,j-1,ans,dp,B);
return ;
}
return ;
}
unsigned long long int solve(int l1,int l2,int i,int j,vector&B,vector<vector> &dp){
if(i>j){return 0;}
if(i==j){
dp[i][j]=l2-l1;
return l2-l1;
}
if(dp[i][j]!=-1){return dp[i][j];}
unsigned long long int ans=l2-l1;unsigned long long int mini=INT_MAX;
mini=min(mini,ans+solve(B[i],l2,i+1,j,B,dp));
int k=i+1;
for(;k<j;k++){
mini=min(mini,ans+solve(l1,B[k],i,k-1,B,dp)+solve(B[k],l2,k+1,j,B,dp));
}
mini=min(mini,ans+solve(l1,B[k],i,k-1,B,dp));
dp[i][j]=mini;
return mini;
}
vector Solution::rodCut(int A, vector &B) {
int n=size(B);
vector ans;
if(n<=1){return B;}
sort(B.begin(),B.end());
vector<vector> dp(n,vector(n,-1));
solve(0,A,0,n-1,B,dp);
order(0,A,0,n-1,ans,dp,B);
return ans;
}