CSES - Fixed-Length Paths I
Authors: Andi Qu, Benjamin Qi
Appears In
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!
We use the same idea as the above solution but with prefix sums instead of a BIT and with small-to-large merging in a single DFS instead of centroid decomposition. This is because we can merge two prefix sum arrays and in time.
If we let denote the maximum depth in node 's subtree, then the resulting time complexity is
Since , the above expression simplifies to .
Below is Ben's code implementing this idea:
C++
#include <bits/stdc++.h>using namespace std;using ll = long long;using db = long double; // or double, if TL is tightusing str = string; // yay python!using pi = pair<int,int>;using pl = pair<ll,ll>;using pd = pair<db,db>;
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!