记忆化搜索出错了,求助
查看原帖
记忆化搜索出错了,求助
139725
brijagstu楼主2022/1/6 15:49

这题我尝试用记忆化搜索没过,哪儿出问题=了?

#include <cstdio>
#include <iostream>
#include <algorithm>
#include <cmath>
#include <numeric>
using namespace std;
int ans = 0;
int dp_state[1000][1000];
int space_cost[1000];
int stuff_value[1000];
int dfs(int space, int stuff){
    if(dp_state[space][stuff] != -1)return dp_state[space][stuff];
    if(space - space_cost[stuff] > 0){
        int d1 = dfs(space, stuff-1);
        int d2 = dfs(space - space_cost[stuff], stuff-1) + stuff_value[stuff];
        dp_state[space][stuff] = max(d1, d2);
    }else{
        dp_state[space][stuff] = dfs(space, stuff-1);
    }
    ans = max(ans, dp_state[space][stuff]);
    return dp_state[space][stuff];
}


int main(){
    memset(dp_state, -1, sizeof(dp_state));
    int space, stuff;
    cin>>stuff>>space;
    for (size_t i = 1; i <= stuff; i++)
    {
        cin>>space_cost[i]>>stuff_value[i];
    }
    for (size_t i = 0; i <= space; i++)
    {
        dp_state[i][0] = 0;
    }
    
    
    dfs(space, stuff);
    cout<<ans<<endl;
}
2022/1/6 15:49
加载中...