Table of Contents
Edit on Githubnull - POI 2016 - Parade
Author: Andi Qu
Time Complexity: .
We want to find a path in the tree with the maximum number of adjacent edges that aren't part of the path.
Any simple path in a rooted tree follows one of two general shapes:
- It only goes up toward the root (from the lowest to the highest node in the path).
- It goes up toward the root and then down again.
Since each path has a single highest node, we can check for each node , what the best paths are for each case if is the highest node in that path. We will do this with dynamic programming.
Let and be the maximum number of adjacent edges for each case with as the highest node. If is the set of children of , then the following recurrences hold:
We can calculate both of these values efficiently by keeping track of the two best values of while iterating through .
Since the path must have a non-zero length though, we also need to subtract 1 from the answer if the graph is a star (i.e. a tree with leaves).
1#include <bits/stdc++.h>2using namespace std;34vector<int> graph[200001];5int dp[2][200001];67void dfs(int node = 1, int parent = 0) {8 int mx1 = 1, mx2 = 1;9 for (int i : graph[node]) if (i != parent) {10 dfs(i, node);
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!