Skip to content
Rain Hu's Workspace
Go back

[LeetCode] 2467. Most Profitable Path in a Tree

Rain Hu

2467. Most Profitable Path in a Tree


一、題目

There is an undirected tree with n nodes labeled from 0 to n - 1, rooted at node 0. You are given a 2D integer array edges of length n - 1 where edges[i] = [ai, bi] indicates that there is an edge between nodes ai and bi in the tree. At every node i, there is a gate. You are also given an array of even integers amount, where amount[i] represents:

Example 1:
eg1

eg2 Example 2:

Constraints:


二、分析

三、解題

1. DFS

int mostProfitablePath(vector<vector<int>>& edges, int bob, vector<int>& amount) {
    vector<vector<int>> graph(amount.size());
    for (const auto& edge : edges) {
        graph[edge[0]].push_back(edge[1]);
        graph[edge[1]].push_back(edge[0]);
    }
    vector<bool> vis(amount.size(), false);
    return dfs(graph, 0, bob, amount, vis, 1)[0];
}

vector<int> dfs(vector<vector<int>>& graph, int alice, int bob, vector<int>& amount, vector<bool>& vis, int round) {
    int res = INT_MIN;
    vis[alice] = true;
    int collide = alice == bob ? 1 : 0;
    for (int& next : graph[alice]) {
        if (vis[next]) continue;
        vector<int> tmp = dfs(graph, next, bob, amount, vis, round+1);
        if (tmp[1] > 0) collide = tmp[1] + 1;
        res = max(res, tmp[0]);
    }
    if (collide > 0 && collide <= round) {
        if (collide == round) amount[alice] >>= 1;
        else amount[alice] = 0;
    }
    return {res == INT_MIN ? amount[alice] : amount[alice] + res, collide};
}

回目錄 Catalog


Share this post on:

Previous
[LeetCode] 2468. Split Message Based on Limit
Next
[LeetCode] 1926. Nearest Exit from Entrance in Maze