E. Nastya and Potions - 记忆化搜索

 

 

 分析:

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

代码:

#include <bits/stdc++.h>

using namespace std;
using ll = long long;

const int N = 2e5 + 10;

ll c[N];
bool st[N];
vector<int> 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';
    }
}

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值