zoukankan      html  css  js  c++  java
  • Magic Maze dfs + dp

    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
    ", 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
  • 相关阅读:
    文件操作
    字典的相关函数
    列表相关操作/列表的相关函数
    字符串相关操作/字符串相关函数
    局部变量 与 全局变量
    函数名的使用
    函数的返回值 return
    命名关键字
    收集参数
    默认形参 与 关键字实参的区别
  • 原文地址:https://www.cnblogs.com/liuweimingcprogram/p/6858440.html
Copyright © 2011-2022 走看看