初学dfs,采用记忆化来处理的背包问题,不知道哪出了问题结果一直略小,求大佬指导

#include<iostream>
#include<algorithm>
using namespace std;
/*
医师把他带到一个到处都是草药的山洞里对他说:“孩子,这个山洞里有一些不同的草药,
采每一株都需要一些时间,每一株也有它自身的价值。我会给你一段时间,在这段时间里,
你可以采到一些草药。如果你是一个聪明的孩子,你应该可以让采到的草药的总价值最大。”
如果你是辰辰,你能完成这个任务吗?
输入
第一行有两个整数T(1  < =  T  < =  1000)和M(1  < =  M  < =  100),
用一个空格隔开,T代表总共能够用来采药的时间,M代表山洞里的草药的数目。
接下来的M行每行包括两个在1到100之间(包括1和100)的整数,
分别表示采摘某株草药的时间和这株草药的价值。
数据规模和约定
对于全部的数据,M  < =  100。
输出
包括一行,这一行只包含一个整数,表示在规定的时间内,可以采到的草药的最大总价值。
*/
int memory[1010][110];
int m, t, ans;
struct y {
    int t, v;
}a[1010];

bool cmp(const y& a, const y& b) {
    return a.t < b.t;
}
int dfs(int cnt, int sum, int time) {
    if (cnt == m||time<a[cnt].t) {
        return sum;
    }
    if (memory[time][cnt] != 0)return memory[time][cnt];
    else {
        int x1 = dfs(cnt + 1, sum + a[cnt].v, time - a[cnt].t);
        int x2 = dfs(cnt + 1, sum, time);
        return memory[time][cnt] = max(x1, x2);//返回节点的最大解并记录
    }
}

int main() {
    cin >> t >> m;
    for (int i = 0; i < m; i++) {
        cin >> a[i].t >> a[i].v;
    }
    sort(a, a + m, cmp);
    cout << dfs(0, 0, t) << endl;
    return 0;
}

在dfs函数中,您应该使用memory[cnt][time]而不是memory[time][cnt]来存储记忆化搜索结果。同时,您需要初始化记忆化数组memory为-1,而不是默认的0,因为0是一个可能的有效结果。以下是修改后的代码:

#include<iostream>
#include<algorithm>
using namespace std;

int memory[110][1010]; // 修改为 memory[cnt][time]
int m, t, ans;

struct y {
    int t, v;
} a[1010];

bool cmp(const y& a, const y& b) {
    return a.t < b.t;
}

int dfs(int cnt, int sum, int time) {
    if (cnt == m || time < a[cnt].t) {
        return sum;
    }
    if (memory[cnt][time] != -1) return memory[cnt][time]; // 修改为 memory[cnt][time]
    else {
        int x1 = dfs(cnt + 1, sum + a[cnt].v, time - a[cnt].t);
        int x2 = dfs(cnt + 1, sum, time);
        return memory[cnt][time] = max(x1, x2); // 修改为 memory[cnt][time]
    }
}

int main() {
    cin >> t >> m;
    for (int i = 0; i < m; i++) {
        cin >> a[i].t >> a[i].v;
    }
    sort(a, a + m, cmp);
    memset(memory, -1, sizeof(memory)); // 初始化 memory 为 -1
    cout << dfs(0, 0, t) << endl;
    return 0;
}