AC - Select Edges

Author: Justin Ji

Table of Contents

ExplanationImplementation

Explanation

To solve this problem, we write a tree DP. Consider that the only factor we need to differentiate nodes on is whether or not we can connect a given node to its parent. Thus, our DP state is the following:

  • dp[u][0]\texttt{dp}[u][0] is the best result in the subtree of uu if we can connect uu to its parent
  • dp[u][1]\texttt{dp}[u][1] is the best result in the subtree of uu if we can't connect uu to its parent

For a given node uu, the "gain" we get from adding this node in is:

(w+dp[u][0])dp[u][1](w + \texttt{dp}[u][0]) - \texttt{dp}[u][1]

Thus, we want to use our d[u]d[u] allowed edges on the nodes that have the most benefit when adding an edge to them. Note that we handle the cases for dp[u][0])\texttt{dp}[u][0]) and dp[u][1]\texttt{dp}[u][1] pretty similarly.

Implementation

Time Complexity: O(NlogN)\mathcal{O}(N\log{N})

C++

#include <bits/stdc++.h>
using namespace std;
using ll = long long;
int main() {
int n;
cin >> n;
vector<int> d(n);

Join the USACO Forum!

Stuck on a problem, or don't understand a module? Join the USACO Forum and get help from other competitive programmers!