I was doing this Spoj problem and written tabulation method which got accepted, then I have written recursive solution but this gave me the wrong solution(WA), Where is my recursive solution is wrong:-
Below is my tabulation solution which got AC:-
#include<bits/stdc++.h> using namespace std; int main(){ int n; cin>>n; int a[n]={0}; int b[n]={0}; for(int i=0;i<n;i++){ cin>>a[i]>>b[i]; } int dp[n][2]={{0}}; dp[0][0]=b[0]; dp[0][1]=a[0]; for(int i=1;i<n;i++){ int x=dp[i-1][0]+abs(a[i]-a[i-1])+b[i]; int y=dp[i-1][1]+abs(a[i]-b[i-1])+b[i]; int s=dp[i-1][0]+abs(b[i]-a[i-1])+a[i]; int t=dp[i-1][1]+abs(b[i]-b[i-1])+a[i]; dp[i][0]=max(x,y); dp[i][1]=max(s,t); } cout<<max(dp[n-1][0],dp[n-1][1]); return 0; }
And below is my recursive solution which is giving me WA:-
#include<bits/stdc++.h> using namespace std; int ans(int a[],int b[],int n,int j){ if(n==0&&j==0) return b[0]; if(n==0&&j==1) return a[0]; int x=ans(a,b,n-1,0)+b[n]+abs(a[n-1]-a[n]); int y=ans(a,b,n-1,1)+b[n]+abs(b[n-1]-a[n]); int s=ans(a,b,n-1,0)+a[n]+abs(a[n-1]-b[n]); int t=ans(a,b,n-1,1)+a[n]+abs(b[n-1]-b[n]); return max(max(x,y),max(s,t)); } int main(){ int n; cin>>n; int a[n]={0}; int b[n]={0}; for(int i=0;i<n;i++){ cin>>a[i]>>b[i]; } if(a[0]>b[0]) cout<<ans(a,b,n-1,1); else cout<<ans(a,b,n-1,0) return 0; }
I want to ask:-
1). What is wrong with my recursive solution.
2). Can we do all dp problem with tabulation and memoization i.e if we can do with memoization than can we do with tabulation and vice versa for every dp problem?