10
COULD SOMEONE EXPLAIN PLEASE ?
source link: https://codeforces.com/blog/entry/117082
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
Could someone explain what did I did wrong for the question 1829D - Gold Rush. When I submitted by recursive code it gets accepted, but when I memoized the code, I am getting TLE. Thanks for explanation in advance. Below is the code,
RECURSIVE
bool solve(int n, int m) {
if(n == m) return true;
if(m > n || n % 3 != 0) return false;
int ind = n / 3;
bool left = solve(ind, m);
bool right = solve(n - ind, m);
return left || right;
}
// Invoking function
bool res = solve(n, m);
MEMOIZED CODE
bool solve(int n, int m, vector<int> &dp) {
if(n == m) return true;
if(m > n || n % 3 != 0) return false;
if(dp[n] != -1) return dp[n];
int ind = n / 3;
bool left = solve(ind, m, dp);
bool right = solve(n - ind, m, dp);
return dp[n] = (left || right);
}
//Invoking function
vector<int> dp(n + 1, -1);
bool res = solve(n, m, dp);
Recommend
About Joyk
Aggregate valuable and interesting links.
Joyk means Joy of geeK