- indexing out of vector size might not throw any error but return a number,
- C++ STL
Sort: inplace sort. You’d better create a new vector for sorting.
// sorted is a vector, and will be changed in place after the below call
sort(sorted.begin(),sorted.end());
Swap:
swap(temp[lind],temp[i]);
Bisection: with a sorted vector, you can use lower_bound
int lind=lower_bound(sorted.begin(),sorted.end(),temp[i])-sorted.begin();
- Dynamic Programming:
Memoization: You can use a reference to the dp matrix in the argument, or create a global variable, or create a map as LRU_cache.
(In python, you can also do them, or even use a LRU_cache package)
// Global Variable defined as the class variable
// initialize to -1, or use memset to set it to something else
int dp[MAXN];
// this function returns the number of
// arrangements to form 'n'
int solve(int n)
{
// base case
if (n < 0)
return 0;
if (n == 0)
return 1;
// checking if already calculated
if (dp[n]!=-1)
return dp[n];
// storing the result and returning
return dp[n] = solve(n-1) + solve(n-3) + solve(n-5);
}
// ****************************************
// a dict as LRU_cache
// this function returns the number of
// arrangements to form 'n'
int solve(int n, unordered_map<int,int>& LRU)
{
// base case
if (n < 0)
return 0;
if (n == 0)
return 1;
// checking if already calculated
if (LRU.find(n) != LRU.end())
return LRU[n];
// storing the result and returning
return LRU[n] = solve(n-1) + solve(n-3) + solve(n-5);
}
// ****************************************
// Use a reference to the dp matrix
int solve(int n, vector<int> & dp)
{
// base case
if (n < 0)
return 0;
if (n == 0)
return 1;
// checking if already calculated
if (dp[n]!=-1)
return dp[n];
// storing the result and returning
return dp[n] = solve(n-1) + solve(n-3) + solve(n-5);
}
- Memset
memset(t, -1, sizeof(t));