Simple template dp

Initialization method seeking Fibonacci number

Initialization method
to perform an initialization operation, performing O (1) complexity of the lookup;

#include <iostream>
#include <cstdio>
using namespace std;
static const long MAX =100000;
int f[MAX];
void init(int n){
    f[0]=1,f[1]=1;
    for(int i=2;i<n;i++){
        f[i]=f[i-1]+f[i-2];
    }
}
int main(){
    init(MAX);
    int n;
    while(scanf("%d",&n)!=EOF){
        printf("%d\n",f[n]);
    }

    return 0;
}

Memory of recursion Fibonacci number

Memory search process
to an initial -1, then the n-input lookup, if DP [n] has been stored, the process returns DP [n]
If not stored, the method recursively request

#include <iostream>
#include <cstdio>
#include <cstring>
using namespace std;
static const long MAX =100000;
int dp[MAX];
int fib(int n){
    if(n==0||n==1)return 1;
    if(dp[n]!=-1)return -1;
    return dp[n]=fib(n-1)+fib(n-2);
}
int main(){
    memset(dp,-1,sizeof(dp));
    int n;
    while(scanf("%d",&n)!=EOF){
        printf("%d\n",fib(n));
    }

    return 0;
}

State transition equation

01 knapsack problem
two-dimensional array:

for(int i=1;i<=物品的数目;i++){
    for(int j=1;j<=背包的容量;j++){
        dp[i][j]=max(dp[i-1][j],dp[i-1][j-w[i]]+v[i]);
    }
}

From 1 reason it is because there is a i-1, in order not to produce unexpected, so w, v, dp arrays are starting at 1
and an array can have from zero

One-dimensional array:

for(int i=0;i<物品的数目;i++){
    for(int j=最大容量;j>=w[i];j--){
        dp[j]=max(dp[j],dp[j-w[i]]+v[i]);
    }
}

Because the capacity is an integer, it is necessary to put all into integer array w, it can be superior in decimal base 10 ^ n, after the last calculated best value for dp, divided by 10 ^ n;

Guess you like

Origin www.cnblogs.com/Emcikem/p/11354215.html