forked from wisdompeak/LeetCode
-
Notifications
You must be signed in to change notification settings - Fork 0
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Create 2378.Choose-Edges-to-Maximize-Score-in-a-Tree.cpp
- Loading branch information
1 parent
d3bcbc9
commit a86f29f
Showing
1 changed file
with
52 additions
and
0 deletions.
There are no files selected for viewing
52 changes: 52 additions & 0 deletions
52
...hoose-Edges-to-Maximize-Score-in-a-Tree/2378.Choose-Edges-to-Maximize-Score-in-a-Tree.cpp
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,52 @@ | ||
using LL = long long; | ||
class Solution { | ||
vector<pair<int,LL>>children[100005]; | ||
LL memo[100005][2]; | ||
public: | ||
long long maxScore(vector<vector<int>>& edges) | ||
{ | ||
int n = edges.size(); | ||
int root = -1; | ||
for (int i=0; i<n; i++) | ||
{ | ||
if (edges[i][0]==-1) | ||
{ | ||
root = i; | ||
continue; | ||
} | ||
int par = edges[i][0]; | ||
int weight = edges[i][1]; | ||
children[par].push_back({i, weight}); | ||
} | ||
|
||
return dfs(root, 0); | ||
} | ||
|
||
LL dfs(int node, int status) | ||
{ | ||
if (memo[node][status]!=0) | ||
return memo[node][status]; | ||
|
||
if (status == 0) | ||
{ | ||
LL sum = 0; | ||
for (auto& [child, weight]: children[node]) | ||
sum += dfs(child, 0); | ||
|
||
LL maxSum = sum; | ||
for (auto& [child, weight]: children[node]) | ||
maxSum = max(maxSum, sum - dfs(child, 0) + dfs(child, 1) + weight); | ||
|
||
memo[node][0] = maxSum; | ||
return maxSum; | ||
} | ||
else | ||
{ | ||
LL sum = 0; | ||
for (auto& [child, weight]: children[node]) | ||
sum += dfs(child, 0); | ||
memo[node][1] = sum; | ||
return sum; | ||
} | ||
} | ||
}; |