CSES - Fixed-Length Paths I
Authors: Andi Qu, Benjamin Qi
Time Complexity:
Given a node , we know that any path in the tree either passes or is completely contained in one of 's children's subtrees. This means that to solve the problem on a tree containing , we can:
- Count the number of paths of length that pass through .
- Remove and its incident edges from the tree.
- Recursively solve the problem on the new trees that are formed.
Counting paths through
We can count the number of paths passing through in a tree of size in time.
We process each of 's children's subtrees in order. Let be the number of nodes we've visited with depth after processing the first of 's children's subtrees. A node with depth in 's -th child's subtree will contribute paths to the answer.
Using two DFSes for each child, we can calculate its contribution and then update in time total.
Applying centroid decomposition
We can combine the previous idea with centroid decomposition to solve the whole problem in time.
When processing some tree, simply let the we use be that tree's centroid. Since the centroid tree has a depth of and each layer in the centroid tree takes amortized time to process, the total complexity is .
Implementation
C++
#include <bits/stdc++.h>typedef long long ll;using namespace std;int n, k;vector<int> graph[200001];int subtree[200001];ll ans = 0;int cnt[200001]{1}, mx_depth;
Bonus Solution
It's also possible to solve this problem in linear time! See the solution for Fixed-Length Paths II for more details.
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!