E. Nastya and Potions - 记忆化搜索

E. Nastya and Potions - 记忆化搜索_第1张图片

 E. Nastya and Potions - 记忆化搜索_第2张图片

 E. Nastya and Potions - 记忆化搜索_第3张图片

 分析:

        dfs永远都需要记忆化搜索,也算是优化技巧吧,首先不知道哪种方法更加好,本质就是找每种材料的最小费用,能通过几种费用更少的材料代替就可以将费用优化成更小,这也就需要dfs来找最小费用,但是会超时,可以在dfs过程中开一个数组优化,进行记忆化搜索,搜过的地方也就不用再进行搜索,直接返回最小值,搜过后的地方数组记录的一定是费用最小值。

代码:

#include 

using namespace std;
using ll = long long;

const int N = 2e5 + 10;

ll c[N];
bool st[N];
vector x[N];
int n, k;

ll get(int u) {
    if(st[u]) return c[u];
    st[u] = true;
    ll sum = 0;
    for(auto j: x[u]) {
        sum += get(j);
    }
    if(x[u].size()) c[u] = min(c[u], sum);
    return c[u];
}

int main() {
    ios::sync_with_stdio(false);
    cin.tie(nullptr);

    int T;
    cin >> T;
    while(T --) {
        cin >> n >> k;
        for(int i = 1; i <= n; i ++) x[i].clear();
        for(int i = 1; i <= n; i ++) st[i] = false;
        for(int i = 1; i <= n; i ++) cin >> c[i];
        for(int i = 0; i < k; i ++) {
            int t;
            cin >> t;
            c[t] = 0;
        }
        for(int i = 1; i <= n; i ++) {
            int m;
            cin >> m;
            while(m --) {
                int t;
                cin >> t;
                x[i].push_back(t);
            }
        }
        for(int i = 1; i <= n; i ++) cout << get(i) << ' ';
        cout << '\n';
    }
}

你可能感兴趣的:(算法,c++,记忆化搜索)