【P1048 采药】 01背包/记忆化搜索

P1048
这道题能写 01 背包和记忆化搜索
本着练习一下记忆化搜索的目的 写了一发记忆化搜索
dp[i][j]代表到第i个东西 剩余容量为j 取得的草药数
首先将dp数组初始化为 -1 然后用以记忆化
因为我们不借助外部参数 val 来返回答案 所以我们是可以记忆化的(对于相同i j 值相同

/*
    if you can't see the repay
    Why not just work step by step
    rubbish is relaxed
    to ljq
*/
#include 
#include 
#include 
#include 
#include 
#include 
#include 
#include 
#include 
#include 
#include 
#include 
using namespace std;

#define dbg(x) cout<<#x<<" = "<< (x)<< endl
#define dbg2(x1,x2) cout<<#x1<<" = "<#define dbg3(x1,x2,x3) cout<<#x1<<" = "<#define max3(a,b,c) max(a,max(b,c))
#define min3(a,b,c) min(a,min(b,c))
#define lc (rt<<1)
#define rc (rt<<11)
#define mid ((l+r)>>1)

typedef pair<int,int> pll;
typedef long long ll;
const int inf = 0x3f3f3f3f;
const int _inf = 0xc0c0c0c0;
const ll INF = 0x3f3f3f3f3f3f3f3f;
const ll _INF = 0xc0c0c0c0c0c0c0c0;
const ll mod =  (int)1e9+7;

ll gcd(ll a,ll b){return b?gcd(b,a%b):a;}
ll ksm(ll a,ll b,ll mod){int ans=1;while(b){if(b&1) ans=(ans*a)%mod;a=(a*a)%mod;b>>=1;}return ans;}
ll inv2(ll a,ll mod){return ksm(a,mod-2,mod);}
void exgcd(ll a,ll b,ll &x,ll &y,ll &d){if(!b) {d = a;x = 1;y=0;}else{exgcd(b,a%b,y,x,d);y-=x*(a/b);}}//printf("%lld*a + %lld*b = %lld\n", x, y, d);
const int MAX_N = 125;
int n,val[MAX_N],V[MAX_N];
ll dp[MAX_N][1025],ans;
int dfs(int tmp,int m)
{
    if(dp[tmp][m]!=-1) return dp[tmp][m];
    if(tmp==n+1)
        return dp[tmp][m] = 0;
    int dfs1,dfs2 = -inf;
    dfs1 = dfs(tmp+1,m);
    if(m>=V[tmp]) dfs2 = dfs(tmp+1,m-V[tmp]) + val[tmp];
    return dp[tmp][m] = max(dfs1,dfs2);
}
int main()
{
    //ios::sync_with_stdio(false);
    //freopen("a.txt","r",stdin);
    //freopen("b.txt","w",stdout);
    int m;
    memset(dp,-1,sizeof(dp));
    scanf("%d%d",&m,&n);
    for(int i = 1;i<=n;++i) scanf("%d%d",&V[i],&val[i]);
    printf("%d\n",dfs(1,m));
    //fclose(stdin);
    //fclose(stdout);
    //cout << "time: " << (long long)clock() * 1000 / CLOCKS_PER_SEC << " ms" << endl;
    return 0;
}

你可能感兴趣的:(ACM,DP)