Magic Maze dfs + dp

本文介绍了一种使用树形动态规划的方法来解决无环图中从每个节点出发所能达到的最大贡献值的问题。通过递归深度优先搜索算法实现,并提供了完整的C++代码实现。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

http://swjtuoj.cn/problem/2387/

设dp[cur]表示以cur这个节点为起点的时候,能走的最大贡献。

题目保证没环,也就是没回路。

感觉和树dp差不多了。

#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <cmath>
#include <algorithm>
#include <assert.h>
#define IOS ios::sync_with_stdio(false)
using namespace std;
#define inf (0x3f3f3f3f)
typedef long long int LL;


#include <iostream>
#include <sstream>
#include <vector>
#include <set>
#include <map>
#include <queue>
#include <string>
#include <bitset>
const int maxn = 2000 + 20;
struct Node {
    int u, v, w;
    int tonext;
}e[maxn * maxn];
int first[maxn], num;
void add(int u, int v, int w) {
    ++num;
    e[num].u = u, e[num].v = v, e[num].w = w;
    e[num].tonext = first[u];
    first[u] = num;
}
int vis[maxn], dp[maxn], DFN;
int dfs(int cur) {
    if (vis[cur] == DFN) return dp[cur];
    vis[cur] = DFN;
    int res = 0;
    for (int i = first[cur]; i; i = e[i].tonext) {
        int v = e[i].v;
        res = max(res, dfs(v) + e[i].w);
    }
    return dp[cur] = res;
}
void work() {
    memset(first, 0, sizeof first);
    int n, m;
    scanf("%d%d", &n, &m);
    for (int i = 1; i <= m; ++i) {
        int u, v, w;
        scanf("%d%d%d", &u, &v, &w);
        u++;
        v++;
        add(u, v, w);
    }
    ++DFN;
    int ans = 0;
    memset(dp, 0, sizeof dp);
    for (int i = 1; i <= n; ++i) {
        if (vis[i] == DFN) continue;
        dp[i] = dfs(i);
    }
    for (int i = 1; i <= n; ++i) ans = max(ans, dp[i]);
    printf("%d\n", ans);
}

int main() {
#ifdef local
    freopen("data.txt", "r", stdin);
//    freopen("data.txt", "w", stdout);
#endif
    int t;
    scanf("%d", &t);
    while (t--) work();
    return 0;
}
View Code

 

转载于:https://www.cnblogs.com/liuweimingcprogram/p/6858440.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值