We need to compute number of ways: remove one edge from original tree, then add one edge (possibly same as removed) to get another tree (so graph remains connected? Actually after removal we have two trees? Wait removal of an edge in a tree disconnects it into two components. Then adding an edge to connect the two components yields a tree again (connected, acyclic). So operation: choose an edge e (to remove) and then choose an edge f to add (could be same as e) such that the resulting graph is a tree and has a perfect matching. But note that after operation, we must have a tree, so f must connect the two components formed by removing e; otherwise if we add an edge within the same component we'd create a cycle, resulting in a tree? Actually if we remove e, we have two trees T1 and T2. Adding any edge between a vertex in T1 and a vertex in T2 will reconnect into a tree. Adding an edge within T1 would create a cycle because T1 is already a tree, resulting in a graph with a cycle, not a tree. So to have a tree, f must connect the two components (any pair with one in each component). So number of possible f is |T1| * |T2| (size of T1 times size of T2). And among those, we also consider f equal to e: that is when we choose the same edge again; it's allowed. So total choices for f given e is |T1| * |T2|.
But we also need that the resulting tree has a perfect matching. So we need to count pairs (e, f) where e is an edge in original tree, and f is a pair (u,v) with u in component A, v in component B (where A,B are components after removing e), such that the tree T' = (V, (E \ {e}) ∪ {f}) has a perfect matching.
We need to compute this efficiently for n up to 5e5.
First, understand condition for a tree to have a perfect matching. Known: A tree has a perfect matching iff for every vertex, when you root it arbitrarily, for each node, you can match it with at most one child, etc. But we need a fast check after edge swap.
Alternatively, we can think in terms of parity and matching properties. A tree has a perfect matching if and only if for every edge, removing that edge splits the tree into two components each of even size? Actually that is a necessary condition? Consider: In a graph with perfect matching, every connected component must have even number of vertices. For a tree with perfect matching, it's true that every component after removing any edge? Not necessarily: In a tree with perfect matching, if you remove an edge that is in the perfect matching, then both components have odd size? Actually if you remove an edge that is in the perfect matching, each component loses one endpoint of the matching edge, so each component has size odd? Let's check: Suppose tree has perfect matching, total n even. Remove an edge e. There are two components. If e is not in the perfect matching, then the matching restricted to each component is a perfect matching of that component? Possibly not, because matching edges might cross e? Actually perfect matching is a set of edges covering all vertices. Since e is removed, but the matching does not include e (if e not in matching), then all matching edges are wholly within one of the two components (because any matching edge connecting across e would have to be e itself). So each component must have even number of vertices for the matching to be perfect on that component. So both components must have even size. If e is in the perfect matching, then the matching edge e is removed, but each component now has an unmatched vertex (the endpoints of e) that are not matched within the component because the matching edge crossing is gone. So each component would have odd size. So for a tree with perfect matching, after removing any edge, one component has even size and the other odd? Actually if e in matching, each component's size is odd (since total even, odd+odd=even). If e not in matching, both even. So the condition "both components even" is not necessary; it's necessary only if the edge is not in the perfect matching. So not a simple parity condition for all edges.
There are known linear-time algorithms to check if a tree has a perfect matching: greedy leaf matching. In a tree, you can repeatedly match a leaf with its parent, remove both, etc. If this process matches all vertices, then a perfect matching exists and is unique (in trees, if a perfect matching exists it is unique). Actually for trees, if a perfect matching exists, it is unique. Is that always true? Consider a path of 4 vertices: edges: 1-2,2-3,3-4. Perfect matchings: {1-2,3-4} and {2-3,?} Actually {2-3, ...} can't cover 1 and 4. So only {1-2,3-4}? But also {2-3, ?} would leave 1 and 4 unmatched, so not perfect. Path of 6? There may be multiple? Consider a star? Star with center and 2 leaves: total 3, no perfect matching because odd. For even tree, I think perfect matching if exists is unique? Let's test: a tree that is a "double-star"? Suppose root with two children each with a leaf: vertices: 1(root),2,3; edges: 1-2,1-3; n=3 odd. Need even. Consider n=6: root with three children each with a leaf? That's 1+3+3? Actually root + 3 children + each child has one leaf gives 1+3+3=7 odd. So need balanced. I recall that trees have at most one perfect matching. Reason: If there were two distinct perfect matchings, consider symmetric difference yields cycles, but trees are acyclic. Actually symmetric difference of two perfect matchings consists of disjoint cycles of even length. In a tree, any cycle would be impossible, so symmetric difference must be empty, thus matchings are identical. So indeed perfect matching in a tree is unique if exists.
Thus we can compute the unique perfect matching for the original tree (if it exists). But we are dealing with many possible resulting trees after edge swap. So we need to count (e,f) such that T' has perfect matching.
We can attempt to characterize when T' has a perfect matching.
Observation: Since T' is a tree on the same vertex set, and n is same (even? Actually n may be even or odd? Perfect matching requires n even. If n is odd, no tree can have perfect matching because perfect matching requires even number of vertices. So if n is odd, answer is 0. Since we are given n maybe any, but output examples include n=4 even, n=5 odd gave 0, n=8 even. So first check: if n odd, answer 0. So assume n even.
Thus we need count for even n.
We have original tree T. Operation: remove e, add f connecting the two components.
Goal: resulting tree T' has perfect matching.
We need to count number of ordered pairs (e,f) with e in original edges, f connecting the two components, such that T' has perfect matching.
Equivalently, for each edge e, we consider the two component sizes s and n-s. For each possible f (any pair across), we ask if T' has perfect matching. But total pairs could be O(n^2) (since s*(n-s) summed over edges could be O(n^2) in worst case like star: edges n-1, each component sizes: for edge connecting center to leaf, sizes =1 and n-1, product = n-1, sum over edges = (n-1)*(n-1) which is ~n^2). So we need faster.
We need to characterize condition on f given e. Perhaps the condition for T' to have perfect matching depends only on e and perhaps on which side the endpoints of f are in relation to the original tree's structure.
Idea: Since perfect matching in a tree is unique if exists, maybe we can compute for each edge whether it is in the perfect matching of T'? But we need existence.
Alternative approach: For a tree, the existence of perfect matching can be determined by a DP: For each node, compute if the subtree can be perfectly matched when the node is free or matched with parent, etc. However we need to evaluate many trees derived by one edge swap. Perhaps we can precompute some data about the original tree's matching structure and then analyze how the change affects.
Let’s denote the original tree T. Suppose T itself may or may not have a perfect matching. But we are not required to keep original matching; we care about existence in T'. So original T's matching may not exist; still some T' may have perfect matching.
We need to understand condition for a tree to have perfect matching. There is a known criterion: A tree has a perfect matching if and only if for every vertex v, the number of "bad" children is something? Actually we can use a greedy algorithm: match leaves with their parents, remove them, repeat. The tree has perfect matching if and only if this process ends with no vertices left. That algorithm is equivalent to: For each vertex, if it has a child that is "unmatched" (i.e., after processing subtrees, the child is free), then you must match the vertex with that child, otherwise the vertex becomes free for its parent. This is like DP: For each vertex, after processing children, if there are an odd number of children that are "free"? Wait more precise: In a rooted tree, define a function: we process leaves upward. The algorithm: While there exists a leaf, match it with its parent, remove both. For tree to be perfectly matched, after removing all, everything vanishes. This algorithm works in any order. It gives a matching if exists; it's unique. So we can compute for each vertex whether its subtree (in original tree) can be perfectly matched leaving some unmatched vertex at root, etc.
But after swapping an edge, the tree changes only by one edge. Possibly we can compute the condition for T' in terms of some data on T.
Observation: The operation "cut e, add f" essentially rewires the connection between two components. Think of it as: originally the two components are connected by e (u-v). After operation, they are connected by f (x-y), where x in component A, y in component B.
Thus T' is the same as taking two trees T_A and T_B (the components after removing e) and connecting them with a new edge between x and y.
We need that the resulting tree T_A ∪ T_B ∪ {x-y} has a perfect matching.
Given two trees T_A and T_B (with known internal structure), plus a connecting edge, we can think: The perfect matching of the combined tree either includes the new connecting edge or not.
If the perfect matching does not include the new edge, then the matching is entirely within each component, so each component must have a perfect matching individually (i.e., both T_A and T_B must have perfect matchings). Because the matching covers all vertices and no edge crosses. So condition: T_A and T_B both have perfect matching (i.e., both have even size? Actually to have perfect matching each must have even size, but also internal structure must allow perfect matching). And then we can combine the matchings.
If the perfect matching includes the new edge (x-y), then after removing x and y (matched together), the remaining parts of T_A (with x removed) and T_B (with y removed) must each have perfect matchings. That is, T_A minus x must have perfect matching, and T_B minus y must have perfect matching. Additionally, x and y are the endpoints of the added edge.
Thus for given T_A and T_B, and chosen x in A, y in B, the combined tree has a perfect matching if and only if either:
- (Case 1) T_A has perfect matching AND T_B has perfect matching, OR
- (Case 2) T_A \ {x} has perfect matching AND T_B \ {y} has perfect matching.
But careful: Could there be a scenario where the perfect matching includes the new edge but also matches some vertices across? No, because only one edge connects A and B. So if the matching includes that edge, it matches x with y, and then the rest must be matched within each component (since no other cross edges). So the conditions are as above.
Thus for a given cut edge e, we have components A and B. For each choice of x in A, y in B, we need that either both A and B are "perfect-matchable" (i.e., have perfect matching) OR both A{x} and B{y} are perfect-matchable.
Note that if both conditions hold, it's fine (but we count it once per (x,y) obviously). However careful: It's possible that both hold, but that doesn't double count because we are counting distinct (x,y) pairs. So we need to count number of (x,y) such that at least one of the two conditions holds.
So our problem reduces to: For each edge e, let A and B be the two components (with sizes s and n-s). For each vertex x in A, define some property; similarly for y in B. Count pairs (x,y) such that either (i) both A and B are "good" (i.e., have perfect matching) OR (ii) both A{x} and B{y} are "good".
Since (i) does not depend on x,y, if A and B both have perfect matching, then all s * (n-s) pairs satisfy condition (i), so they all count. However we must ensure we don't double count if also (ii) holds for some of those, but that's okay (we count each pair once). So for a given e, the number of valid f = s*(n-s) if both components are perfect-matchable? Wait check: If A and B both have perfect matching, then for any x,y, condition (i) holds, so all pairs are valid. So answer contribution for that e is s*(n-s).
But is that always correct? Let's test with simple example. Example 1: n=4, tree is path 1-2-3-4. Components after cutting each edge? Edge 2-3: components: A={1,2}, B={3,4}. Both A and B are edges, each have perfect matching? A has vertices 1 and 2, perfect matching exists (the edge itself). B similarly. So both perfect-matchable. So all pairs across: |A|=2,|B|=2, product=4. But in example output total 8, and for edge 2-3, they listed several ways including turning to 1-3,1-4,2-3,2-4. That's 4 possibilities for this edge. Yes matches. For edge 1-2: components A={1}, B={2,3,4}. A size 1 (odd) cannot have perfect matching (since perfect matching requires even number). B size 3 odd also cannot have perfect matching. So (i) fails. So need to consider (ii). For each x in A (only x=1), we need A{x} = empty (size 0) which trivially has perfect matching (empty set of vertices? Usually perfect matching on empty set is vacuously true). B{y} must have perfect matching. For which y in B does B{y} have perfect matching? B = {2,3,4} with edges 2-3,3-4? Actually B is the subtree induced by vertices 2,3,4 with edges 2-3,3-4? Wait original tree: edges: 1-2,2-3,3-4. Removing edge 1-2 leaves component A={1}, component B={2,3,4} with edges 2-3 and 3-4. For B{y} to have perfect matching, we need the induced tree on B minus y to have perfect matching. Compute: For y=2, B{2} = {3,4}, which is an edge, perfect matching exists. For y=3, B{3} = {2,4}, but there is no edge between 2 and 4 (since edges are 2-3 and 3-4, removing 3 leaves isolated vertices 2 and 4, no edge, so they cannot be matched? Actually a perfect matching on a set of two vertices requires an edge between them. Since there is no edge, no perfect matching. So fails. For y=4, B{4} = {2,3}, which is edge 2-3, perfect matching exists. So y=2 and y=4 work. So (ii) holds for x=1 and y in {2,4}. That gives 2 pairs. But also note that if both A and B have perfect matching? No. Also maybe there could be the case where (i) fails but (ii) works. So edge 1-2 contributes 2 pairs. Similarly edge 3-4 by symmetry contributes 2 pairs. Total 4+2+2=8, matching example. Good.
Thus the characterization seems correct.
Now we need to compute for each edge e, the number of pairs (x in A, y in B) such that either:
- Both A and B have perfect matching (call condition C0), which gives all pairs.
- Else, count pairs where A{x} has perfect matching AND B{y} has perfect matching (condition C1(x,y)).
But careful: If C0 holds, then we count all pairs, and there is no need to consider C1 separately because they are already counted. But we can just compute total = if C0 then s*(n-s) else count of pairs satisfying C1. However there might be edges where both C0 and some C1 pairs hold? But if C0 holds, then both A and B have perfect matching. In that case, for any x,y, does A{x} have perfect matching? Not necessarily. For instance, A is a tree with perfect matching, but if you remove a vertex, it may not have perfect matching. So C1 may not hold for all pairs. But since we are counting all pairs already from C0, we don't need to add extra; we just count all pairs. So for edges where C0 is true, answer contribution = s*(n-s). For edges where C0 is false, we need to count number of x,y such that A{x} and B{y} both have perfect matching.
But wait: Could there be an edge where C0 is false but some pairs also satisfy C0? No, C0 is property of whole components independent of x,y. So it's either true or false. So if false, we only count C1 pairs. But ensure that there is no double counting across C1 and something else? That's it.
Now we must also consider the possibility that the perfect matching of T' might involve the new edge but also possibly match some vertices across? As argued only cross edge is f, so if matching includes f, then it's covered; else it's internal. So conditions are exhaustive.
Thus the problem reduces to, for each edge e (cut), we need:
- Determine if component A (the subtree when cut) has a perfect matching (as a tree by itself). Similarly for B.
- If both yes, then contribution = |A| * |B|.
- Else, we need for each vertex x in A, know whether A{x} has perfect matching; similarly for each y in B. Then contribution = count_A_good * count_B_good, where count_A_good = number of x in A such that A{x} has perfect matching, and count_B_good similarly.
But is that sufficient? Consider possibility where both conditions (i) and (ii) might both be true for some pairs? If both are true, then we count the pair once. Our counting method: if C0 true, we count all pairs, which includes those that also satisfy C1. That's fine. If C0 false, we count only C1 pairs. So no double counting.
But wait: Could there be a scenario where the perfect matching of T' uses the new edge, but also one of the components after removal of x and y might have perfect matching even if A{x} and B{y} have perfect matching? That's exactly condition (ii). However, there is a subtlety: The matching that includes the new edge must match x with y. For that to be possible, we need that there exists a perfect matching of T' that includes (x,y). Our condition that A{x} and B{y} each have a perfect matching ensures that such a matching exists: take perfect matchings of A{x} and B{y} and add edge (x,y). But is it sufficient that each subgraph individually has a perfect matching? Since the components are separate, yes. However, we must also ensure that the edge (x,y) exists? Yes we are adding it. So condition (ii) is sufficient. Is it necessary? If T' has a perfect matching that includes (x,y), then removing x,y yields perfect matchings on the remainders. So condition (ii) is also necessary. So it's exactly necessary and sufficient.
But there is also possibility that the perfect matching does not include the new edge, but A and B individually have perfect matchings. That's condition (i). So indeed our conditions are complete.
Thus the problem reduces to computing for each edge cut, the sizes and these properties.
Now, we need to process all edges efficiently (O(n) or O(n log n)). n up to 5e5.
We can root the tree arbitrarily, say at 1. Then each edge separates the tree into a "child subtree" and the rest. For each edge (parent-child), we can consider the component that is the subtree of the child, and the component that is the complement (the rest). So we need to compute for every possible component (subtree and complement) whether it has a perfect matching, and for each vertex, whether the component (subtree or complement) minus that vertex has perfect matching.
Let’s denote for the whole tree T (original) we can compute some DP to determine perfect matching existence and perhaps more. But we need these properties for many subgraphs that are subtrees (connected) after removing an edge. Actually each component is a tree (since original is tree). So both components are trees.
We need to compute for every possible tree that is a subtree (by cutting an edge) or its complement, the two properties: (1) Does it have a perfect matching? (2) For each vertex in that tree, does the tree minus that vertex have a perfect matching?
If we can compute for each vertex, for each "component" that it belongs to when considering a cut edge, whether that component minus that vertex has perfect matching, then we can compute contributions.
However, note that for a given cut edge e, we need the product of counts across the two sides. So we need count_A_good = number of vertices x in A such that A{x} has perfect matching; similarly for B.
Thus if we precompute for each vertex v and for each possible component that is defined by cutting an edge adjacent to v (maybe the component that does NOT contain a particular neighbor), we can aggregate.
Given the tree, edges are n-1. For each edge e = (u,v), we have two components: the subtree of v when rooting at u (call it subtree S_v) and the complement (rest). We can treat the tree as rooted. So for each directed edge (parent->child), we can compute data for the subtree rooted at child, and for the "outside" of that subtree (the rest). Then the cut edge corresponds to that undirected edge; we can combine data from both sides.
Thus we need to compute for every node as root of some subtree (the child subtree) the following:
- size of subtree: sz[v] (when rooted at 1, but careful: for each edge parent-child, the child subtree is defined relative to that root. If we fix root 1, then for each child, its subtree is the set of descendants. The complement is the rest.)
- does the subtree have a perfect matching? Let's denote match[v] = boolean indicating whether the subtree rooted at v (with the edge from parent to v considered as part of the subtree? Actually the subtree as a tree includes v and its descendants, and the edges among them. It is a tree. So we can compute via DP whether that tree has a perfect matching. But note: For a tree that is a component after cutting, it is not necessarily rooted; but any tree structure. However we can still compute using DP on the rooted version; but the property of having perfect matching is independent of rooting. So we can compute for each node v (considering its subtree in the rooted tree) whether the induced tree on that set (which is not necessarily the same as the subtree rooted at v? Actually if we root at 1, then for a node v, the set of its descendants together with v forms a connected subtree that is exactly the component you get if you cut the edge from v to its parent (assuming v is not the root). So indeed for each non-root node, the component that is the child side of the edge (parent,v) is the subtree of v when root at 1. For the root, we don't have such, but we consider edges from root to children; then the child's subtree is as defined; the complement is the rest (including root and other subtrees). So we can compute for each node v (considering the subtree rooted at v) whether that subtree has a perfect matching. But careful: For a subtree rooted at v, the tree is exactly that component, so it's fine.
Now for the complement side (the rest of tree after removing the subtree of v), that is also a tree, but not necessarily rooted conveniently. However we can compute DP for the whole tree with rerooting technique to get for each node, the data for the "tree when considering that node as root" but we need data for the component that is the complement of a subtree. That component is essentially the tree formed by removing v's subtree from the whole tree; it is connected and contains parent of v and all other parts. That component can be thought of as the tree rooted at the parent but with the child's subtree removed. We can compute for each node v (non-root) the properties of the "outside" component, using DP from both sides.
Similarly, we need for each vertex x in a component (subtree or complement), whether the component minus x has perfect matching. So we need for each vertex x, for each component that x belongs to in cuts that separate that component from the rest via some edge, the property "does the component minus x have perfect matching?" But note: For a given cut edge e, the component A may be either the subtree of some node or its complement. So we need to compute for each vertex x and for each edge e where x is in the component A (the side we consider) the boolean value f_A(x) = 1 if A{x} has perfect matching, else 0. Then for a given e, count_A_good = sum_{x in A} f_A(x). Similarly for B. So we could compute for each possible component (which is defined by an edge) the total count of "good" vertices (those whose removal yields perfect matching) within that component.
Thus the problem reduces to: For each edge e (parent-child direction), we need to know:
- size of child subtree sz_child,
- whether child subtree has perfect matching (call match_sub),
- number of vertices in child subtree that, when removed, leave the subtree with perfect matching (call good_sub_count).
And similarly for the complement side:
- size_comp = n - sz_child,
- whether complement has perfect matching (match_comp),
- good_comp_count = number of vertices in complement such that complement minus that vertex has perfect matching.
Then for the undirected edge e, if match_sub and match_comp are both true, then contribution = sz_child * (n - sz_child). Else contribution = good_sub_count * good_comp_count.
But careful: The complement side for edge e is the same as for the reverse direction; we need to compute for each directed edge. So we can process each undirected edge once, using the data from both sides.
Thus we need to compute for each node v (considering its subtree when rooted at 1) the three values: size, match (boolean), good_count (number of vertices w in subtree such that subtree \ {w} has perfect matching). For the complement side, we can compute for each node v (non-root) the same three values for the component that is the whole tree minus v's subtree. Also, we need to handle the root? The root is not a child, but edges from root to children: for child's side we have subtree values; for root's side (the complement) is the rest of tree excluding child's subtree. That complement includes root and other subtrees; we can compute its properties similarly using rerooting.
Thus we need to compute these for all "subtrees" that arise by cutting an edge: both the subtree (child's side) and the complement. To compute match and good_count for arbitrary connected induced subgraphs that are trees, we can use DP on tree with rerooting.
First, let's focus on computing for any rooted tree (the whole tree) the match status of the whole tree. Then for a subtree (like the subtree of v), we can compute using DP from leaves upward. For a component that is the complement of a subtree, we can compute by considering the whole tree and "removing" that subtree. This is like rerooting: treat the parent side as providing additional children.
We need two main DP passes: one DFS to compute subtree info, and a second DFS to propagate info from parent to child to compute the data for the complement of child's subtree (i.e., the tree consisting of the whole tree minus child's subtree). This is typical for problems that require answers for each edge.
Now we need to define the DP for a tree (any tree) to determine:
- Does it have a perfect matching? (size even is necessary, but not sufficient)
- For each vertex, does the tree minus that vertex have a perfect matching? (we need count of such vertices)
We need to compute these efficiently for many trees (each component). But note that each component is a tree that is either a subtree in the rooted sense (descendant set) or the complement. The total number of components we need to evaluate is O(n) (each edge gives two components, but many components are repeats? Actually each edge gives two distinct components; there are 2*(n-1) components considered, but each component is uniquely associated with a directed edge: for child subtree, it's that subtree; for complement, it's the complement of that subtree. However the complements may be the same for different edges? For edge (parent,child), complement is the whole tree minus child's subtree. Different children of the same parent have different complements? For child1, complement = rest of tree (including parent and other subtrees). For child2, complement is also rest, but they are not identical because they exclude different subtrees. So they are different sets. So total 2*(n-1) components, each a tree (connected). That's O(n) components. So we can compute their properties individually if we can do it in O(1) or O(log n) each after preprocessing.
So we need to compute for each node v (as root of its subtree) and also for each node v (as root of the complement side? Actually complement side is not rooted at a particular node; but it's a tree and we can compute its properties using DP with v's parent as root maybe.
Idea: For each node, we can compute data for the tree that is "the component when the edge from parent to v is cut, on the parent side". That component can be thought of as the tree rooted at the parent, but with the child v's subtree removed. We can compute its properties using rerooting: essentially we want to compute for each node, the DP values for the whole tree when considering that node as the root? But the complement is not exactly the whole tree rooted at parent; it's the tree formed by taking parent and all other subtrees except v's. That is like the tree where we cut off v's subtree. So we could compute for each node u, the DP values for the tree consisting of all nodes except the subtree of a particular child v. That can be computed using a technique of "DP on tree with pruning" using prefix/suffix aggregations over children.
Thus we can compute for each directed edge (parent->child) the necessary three values for both sides using two DFS passes.
Now we need to define the DP for a tree to compute:
- size: number of vertices.
- match: boolean if the tree has a perfect matching.
- good_count: number of vertices in the tree whose removal results in a perfect matching.
We need to compute these for a tree quickly given its structure. However, these values are not simple aggregates from children alone; they depend on the structure and the matching.
Since perfect matching in a tree is unique if exists, we can compute it greedily via a leaf matching algorithm. Alternatively, we can compute via DP: For each node, we can compute whether its subtree (rooted) can be perfectly matched, and also maybe count of vertices whose removal yields perfect matching.
But note that the components we consider are trees themselves. We need to compute for each such component its properties. However, we cannot run a separate DP for each component; we need to compute all in O(n) total. So we need to define DP that can be computed bottom-up for subtrees, and also "reroot" to compute for complements.
Let's analyze the properties more deeply.
First, determine if a tree has a perfect matching. There is a classic linear time algorithm: perform a DFS, and for each node, after processing children, if there is any child that is "unmatched" (i.e., its subtree is perfectly matched except the child itself is free), then you match the node with that child; otherwise the node becomes free. More formally, we can define a DP: For a rooted tree (arbitrary root), define status dp[v] = maybe the size of the unmatched vertices in subtree? Actually we can compute whether the whole tree can be perfectly matched, but also we may need to know, for each vertex, if removal of that vertex yields a perfect matching.
Let's think about the unique perfect matching property. For a tree that has a perfect matching, the matching is unique. In such a tree, each vertex is either matched with its parent or with one of its children, depending on the matching. Actually we can determine the matching by a greedy leaf removal: repeatedly take a leaf, match it with its parent, remove both, continue. This yields the matching if exists.
We can use this process to characterize vertices that are "essential" maybe.
Alternatively, we can compute for each node v, the size of its subtree (in the original tree). But that alone is insufficient.
Let's derive necessary and sufficient conditions for a tree to have perfect matching in terms of DP.
Define a rooted tree. Let f(v) = 0/1 indicating whether the subtree of v (including v) can be perfectly matched (i.e., all vertices in the subtree are matched within the subtree). But this is only possible if the subtree size is even. However, even size is not sufficient. Actually, if we root arbitrarily, the condition for the whole tree to have perfect matching is that there exists a matching covering all vertices. The DP can be: For each node, we consider matching with some child, etc. But maybe it's easier to compute the matching itself via the greedy algorithm and then derive properties.
Let’s consider the unique matching M (if exists). For a tree, if it has a perfect matching, we can compute it by the following algorithm: Mark all vertices as alive. While there is a leaf, take a leaf u, let p be its parent (unique). Match u with p. Remove u and p from the tree (i.e., mark them as removed). Continue. If at the end all vertices are removed, then a perfect matching exists; otherwise, no perfect matching. This algorithm is correct and yields the unique matching.
Using this algorithm, we can compute for each vertex whether it is matched with its parent or a child, etc. Moreover, this process is deterministic and independent of the order: it's essentially a bottom-up elimination. It is similar to the concept of "maximum matching" in trees, but for perfect matching we require full coverage.
Thus we can simulate this elimination on the whole tree to determine which edges are in the matching, and which vertices get matched with which. However, we need to apply this to many different trees (components). Can we compute the elimination process on the original tree and then deduce for subgraphs? Possibly via a concept of "critical vertices" or "states".
Observation: The elimination process on a tree depends on the degrees and structure. However, if we take a subtree (connected induced subgraph) of the original tree, its elimination may be affected by the rest of the tree if the subtree shares an edge with the rest? But when we consider a component after cutting an edge, it is a tree by itself, with no connections to the outside. So we need to run the elimination on that component independently. So we need to know for each possible tree (subtree or complement) its perfect matching property. This is like we need to know for each induced connected subgraph that is a tree (and specifically those that are components after cutting an edge) whether it has a perfect matching.
There might be a way to compute these properties using DP that can be aggregated and then used with rerooting.
Given the complexity, maybe we can derive simpler conditions for a tree to have perfect matching in terms of its "deficiency" or "Tutte condition"? For bipartite graphs, Hall's condition, but tree is bipartite. However perfect matching in bipartite graph exists if and only if each subset S on one side has neighborhood at least |S|. But tree is bipartite; we could choose bipartition. But then condition becomes: for every subset of one partition, its neighbors are at least as many. That's nontrivial to check for many subgraphs.
Alternatively, we could compute for each vertex a "status" like "matched with parent" or "matched with child" based on the whole tree's matching, but that matching is for the whole original tree, not necessarily for subcomponents. However, maybe the condition for a component to have a perfect matching is equivalent to some condition on its size and on the statuses of the cut edge? Let's test with examples.
Consider original tree with perfect matching? For edge 1-2 in the first example, original tree path 1-2-3-4. Does original tree have perfect matching? Yes, the matching is {1-2,3-4}. So both components after cutting 1-2: A={1}, B={2,3,4}. A size 1, cannot have perfect matching. So condition for component B to have perfect matching? B as a tree has no perfect matching because size 3 odd. So not both have perfect matching. For condition (ii), we need A{1} = empty (size 0) which is perfect matching; B{2} = {3,4} has perfect matching. So it works. In terms of original matching, note that the original matching edge 1-2 is cut; 1 is matched to 2 originally. After cutting, B{2} leaves {3,4} which is matched originally. So maybe the condition relates to whether the removed vertex is matched to a vertex in the other component? Hmm.
Consider edge 2-3 in same tree. Original matching edges: 1-2,3-4. Cutting edge 2-3: components A={1,2}, B={3,4}. Both have perfect matching. So condition (i) holds.
Consider edge 3-4 similar to 1-2.
So for this tree, edges that are in the perfect matching (1-2,3-4) produce condition (i) false, while the edge not in the matching (2-3) gives condition (i) true. But is this general? Not necessarily. Let's test on a different tree.
Example 3: Input 8, let's analyze. Original tree: edges: 1-2,2-3,3-4,1-5,5-6,6-7,1-8. So structure: 1 connected to 2,5,8. 2-3-4 chain, 5-6-7 chain. n=8 even. Does this tree have a perfect matching? Possibly yes? Let's try to find matching: We can try leaf matching: leaves: 4,7,8? Also maybe others. Leaf 4: match with 3, remove 3 and 4. Then leaf? now 3 removed, so node2 maybe leaf? Then leaf 7: match with 6, remove 6,7. Then leaf? maybe 6 removed, so 5 leaf? then match 5 with 1? But 1 also connected to 2 and 8. After removing 3,4 and 6,7, we have vertices: 1,2,5,8. Edges: 1-2,1-5,1-8. That's a star of 1 with 3 leaves. To perfectly match, we need to match 1 with one leaf, leaving two leaves unmatched. So fails. Alternate order: start with leaf 8: match 8-1, remove both. Then leaves: 4,7. Match 4-3, remove 3,4. Leaves: maybe 2? Now vertices: 2,5,6,7? Actually after removing 1 and 8, edges: 2-3? 3 still there? Wait we removed 1 and 8. Remaining: 2,3,4,5,6,7. Edges: 2-3,3-4,1-5? But 1 is removed, so edge 1-5 is gone? Actually if we remove 1, edge 1-5 disappears. So 5 becomes isolated? Let's check: original edges: 1-5,5-6,6-7. If we remove vertex 1, edge 1-5 is gone, but 5-6 and 6-7 remain, so 5,6,7 are still connected (chain 5-6-7). So after removal of 1 and 8, we have components: {2,3,4} path and {5,6,7} path. Both have odd sizes (3 and 3). They cannot be perfectly matched. So no perfect matching. So original tree does not have perfect matching. So the condition for components after cut does not simply depend on original matching.
We need to compute these component properties from scratch.
Thus we need an algorithm to compute for each subtree (as defined by a rooted tree) and for each complement tree, the three values: size, hasPerfectMatching, and goodCount (number of vertices whose removal yields perfect matching). Let's denote for a tree T:
- size(T)
- perfect(T) = 1 if T has perfect matching, else 0.
- good(T) = number of vertices v in T such that T \ {v} has perfect matching.
We need to compute these for O(n) trees quickly.
We can attempt to design DP to compute perfect(T) for any tree efficiently if we can combine children. Since trees are small? But we need many trees.
Observations: The property perfect(T) and good(T) might be derived from some DP that computes for each vertex its "state" in terms of the matching process. The elimination algorithm (leaf matching) can be used to determine which vertices are matched with which.
Let's formalize the leaf matching process on a tree:
Initialize all vertices as unmarked. While there exists a leaf (vertex with degree 1) among unmarked vertices, pick such leaf u. Let v be its unique neighbor that is unmarked. If v is also unmarked, then match u with v, and mark both u and v (remove them). If v is already marked (i.e., already matched with some other leaf), then this leaf cannot be matched? Actually in the algorithm, we always pick a leaf and match it with its parent, and then remove both. If at some point a leaf's parent is already removed, that would be a problem, but since we always remove both, we only pick leaves whose neighbor is still present. However, it's possible that after some removals, a vertex may become a leaf but its only neighbor might already be matched? Actually the algorithm as described works because when we remove a matched pair, the degrees update. The process is deterministic if we always pick any leaf. The existence of perfect matching is equivalent to that this process ends with all vertices matched (no vertex left). This algorithm is essentially the same as checking if the tree is "matchable".
Now, note that the outcome of this process (which vertices get matched to which) is independent of the order of picking leaves, as long as we always pick a leaf and match it with its neighbor and remove both. This can be proven by uniqueness of maximum matching in trees? Actually the matching obtained is the unique maximum matching? For trees, the greedy leaf removal yields the maximum matching, but for perfect matching, if it exists, the maximum matching is perfect and unique. So indeed the process yields the unique perfect matching if exists.
Thus we can run this elimination on any tree and get a set of matched edges. But can we compute perfect(T) quickly for many subtrees using DP? Perhaps we can compute a "matching status" for each vertex relative to its parent in the original tree? But the subtree's structure is different.
Alternatively, we could compute for each vertex v a "type" based on the whole tree's leaf elimination, but that doesn't directly give perfect matching for arbitrary subtrees.
Maybe we can use DP that for a rooted tree computes two values:
- dp0(v): whether the subtree of v can be perfectly matched (i.e., all vertices in subtree matched within subtree). This requires the subtree size even.
- dp1(v): maybe whether the subtree of v can be matched such that v is "free" (unmatched) and the rest are perfectly matched. That would mean subtree size odd, and after removing v, the rest have perfect matching.
But the perfect matching of a tree is a global property; we can compute using DP on tree.
Standard DP for matching in trees: For each node, consider matching it with one of its children or not. We can compute a boolean indicating if the subtree can be perfectly matched, and also maybe count of vertices whose removal yields perfect matching.
But we need this DP not only for subtrees rooted at children in the original rooting, but also for arbitrary trees that are complements. However, we could compute DP for the whole tree in a rooted fashion, then use rerooting to compute for any node as root, the DP values for the tree when rooted at that node (i.e., considering entire tree). But we need for subtrees that are not the whole tree. The complement of a subtree is not a subtree in the rooted sense, but we could treat it as a tree rooted at the parent node, with the child's subtree excluded. That can be handled by rerooting with "exclusion" of a child.
Thus we need DP that is "tree DP with ability to cut out a child". This suggests we can compute for each node, DP for its subtree (as usual), and also for each node, DP for the "full tree except the subtree of a specific child" by using DP from the parent combined with contributions from other children.
So overall, we can compute for each directed edge (parent->child) the following:
- For the child side: subtree = child's subtree (as rooted at child). We can compute its properties with a standard DP on the original rooted tree (since that subtree is exactly the set of descendants when root is 1).
- For the parent side: complement = whole tree minus child's subtree. This can be seen as the tree rooted at parent but with the child removed. We can compute its properties using DP that aggregates contributions from all other children of parent, plus the part "above" parent (i.e., the rest of tree beyond parent). So we need to compute for each node, the DP values for the tree "above" it (the part outside its subtree when rooted at 1). Then for a child, the complement is essentially the tree formed by taking the parent's "upward" part plus the parent and all other children subtrees.
Thus we can design a DP that for each node computes:
- size_sub[v] = size of subtree rooted at v.
- perfect_sub[v] = 1 if subtree(v) has perfect matching.
- good_sub[v] = number of vertices x in subtree(v) such that subtree(v) \ {x} has perfect matching.
But careful: good_sub[v] is count of vertices within subtree(v) that, if removed, the remaining tree (which is subtree(v) minus that vertex) has perfect matching. Note that this remaining tree might be disconnected (since removing a vertex splits the subtree into components). But perfect matching of that forest (which is a tree minus a vertex may become a forest) needs to be a perfect matching covering all vertices of that forest. Since it's a forest (multiple trees), we require that each connected component has a perfect matching. Since the forest's components are the subtrees of the children after removing v (and possibly connecting? Actually if we remove v, the remaining graph consists of the subtrees of each child of v (each child's full subtree) as separate trees (since v was the connection). So we need that each of these child subtrees individually has perfect matching. Because there are no edges between them. So the condition for subtree(v) \ {x} to have perfect matching is: if x = v, then we need that each child's subtree of v has perfect matching (since after removing v, we have independent subtrees for each child). If x is in some child's subtree, say in subtree of child c, then we need that subtree(c) \ {x} has perfect matching, and all other child subtrees of v have perfect matching, and also maybe v itself? Wait if we remove x (which is not v), then v remains. The remaining graph is v plus all child subtrees, but with one child subtree missing x. The structure: v is connected to each child subtree (via the child). After removal of x, the tree may split if x is an articulation point. Actually if x is not v, and we remove x, the graph may become disconnected: the subtree of child c is rooted at c, but when we remove x, that subtree may split into components: if x is not c, then after removal, the component containing c (if x != c) might still be connected to v via c (if c is not removed). Actually we need to consider the induced subgraph on subtree(v) \ {x}. Since the original tree is rooted at v, each child c is directly connected to v. If we remove a vertex x that lies in the subtree of child c, there are two cases:
- If x = c, then edge v-c is removed (since c gone), leaving v connected to other children, and the grandchildren subtrees of c become separate components (each child of c becomes a root of its own component). So we need that v's remaining part (v plus all other child subtrees) and each component from c's children subtrees all have perfect matchings.
- If x is deeper, then the removal of x may split the subtree of c into multiple components: one containing c and possibly some parts, and others containing subtrees of children of x. The component containing c remains connected to v via the edge v-c (since c still present). So the tree becomes: v connected to c, and from c we have a modified subtree (with x removed). So we need that the component containing v and the rest of the tree can be perfectly matched.
Thus computing good_sub[v] requires considering removal of any vertex in subtree. This seems complex if we try to compute counts directly.
But maybe we can find a simpler characterization for "good" vertices (those whose removal yields perfect matching) in a tree.
Observation: For a tree T (with even number of vertices), it has a perfect matching M (if exists). Then what vertices v have the property that T \ {v} has a perfect matching? Since T has perfect matching, removing v destroys that matching; we need a new perfect matching on T{v}. T{v} has odd number of vertices? Actually if T has even size, removing v gives odd size, so cannot have perfect matching because perfect matching requires even number of vertices. Wait! That's crucial. Perfect matching on a graph requires covering all vertices. If we remove a vertex, the number of vertices becomes odd (since originally even), so perfect matching cannot exist because it would leave one vertex unmatched. So for a tree T that itself has perfect matching, T{v} cannot have a perfect matching because the vertex count becomes odd. So good(T) can only be non-zero if T itself does NOT have a perfect matching? Actually wait, definition: For a component A, we consider A{x} has perfect matching. This requires that |A| - 1 is even (since perfect matching requires even number of vertices). So |A| must be odd. So A itself must have odd size for A{x} to possibly have perfect matching. Because if |A| is even, then |A|-1 is odd, impossible. So good vertices only exist in components of odd size. Moreover, if |A| is odd, we ask whether removing a specific vertex yields a graph (forest) with perfect matching. That forest would have even number of vertices (odd-1 = even). The forest consists of several trees (since removing a vertex may disconnect the tree). For the forest to have a perfect matching, each connected component must have a perfect matching (since no edges between components). So the condition is: removing x, the resulting forest (each component being a tree) all have perfect matching.
Thus for a component A (a tree), if |A| is even, then perfect(A) may be true or false; but good(A) = 0 because size becomes odd after removal. Actually if |A| is even, then |A|-1 is odd, so impossible to have perfect matching covering all vertices (since perfect matching requires even number). So good(A) = 0 automatically. Therefore, in our counting for a component A, we only care about good(A) when |A| is odd. In the case where condition (i) fails, we are counting pairs where both A{x} and B{y} have perfect matching. Since A and B are the two components after cutting, we have |A| + |B| = n (even). So if |A| is odd, then |B| is odd as well because even - odd = odd. So both sizes are odd. Then A{x} and B{y} have even sizes (odd-1 = even) and can possibly have perfect matching. So good(A) and good(B) are counts of vertices in odd-sized components whose removal yields perfect matching.
So we only need to compute good(A) for components of odd size (and similarly for even sized components, it's zero, but we may still need to know perfect(A) for even sizes for condition (i)). So our DP should compute perfect(T) for any tree, and for trees of odd size, we also need good(T) = number of vertices x such that T{x} has perfect matching.
Now note that for even-sized trees, perfect(T) may be true or false; good(T)=0. For odd-sized trees, perfect(T) is false (since perfect matching requires even number), so we don't need perfect(T) for odd trees except perhaps for some other uses? In condition (i) both A and B need to have perfect matching, which implies both sizes even. So for condition (i), both components are even-sized. For condition (ii), both components are odd-sized (since sizes sum to even, and they cannot be one even one odd because then sum would be odd? Actually even+odd = odd, but n even, so sum of sizes is even. So if one is even, the other must be even. If one is odd, the other must be odd. So condition (i) corresponds to both even and perfect; condition (ii) corresponds to both odd and both have at least one vertex whose removal yields perfect matching? Actually both A and B odd, and we need A{x} perfect and B{y} perfect. So each of A and B must be such that there exists at least one vertex whose removal yields perfect matching. So we need good counts for odd-sized components.
Thus overall, for each cut edge e, we need:
- If both components have even size and both are perfect, then contribution = |A|*|B|.
- Else if both components have odd size, contribution = good(A) * good(B). (If either component has even size but not perfect? Then condition (i) fails, and condition (ii) cannot hold because odd/even mismatch? Actually if one even, one odd, then condition (ii) requires both A{x} and B{y} perfect, but then |A| even => |A|-1 odd, so A{x} cannot be perfect. So condition (ii) impossible. So contribution 0.)
So we can compute contribution per edge based on parity and these properties.
Thus we need for each component (subtree or complement):
- size parity (even/odd)
- if even: whether it has perfect matching (boolean)
- if odd: good count (number of vertices whose removal yields perfect matching)
Also note: For even-sized component, perfect(T) might be true or false; for odd-sized, perfect(T) is false always, but we don't need it. good(T) defined for odd-sized components.
Now we must compute these efficiently.
So we need to compute for each directed edge (parent->child) the above data for the child's subtree (size_sub, is_even, perfect_sub if even, else good_sub if odd) and for the complement (size_comp, perfect_comp if even, good_comp if odd). Then for each undirected edge we combine.
Now we must design DP to compute these for subtrees rooted at each node and for complements.
Let's first consider computing for a given tree (subtree rooted at v) its properties. We need to compute two things: for even size, whether it has perfect matching; for odd size, count of vertices whose removal yields perfect matching.
We can compute these using DP on tree with states. Since perfect matching in a tree is unique if exists, perhaps we can compute it via a matching algorithm. But we also need the good count for odd-sized trees. Could there be more than one vertex whose removal yields perfect matching? Possibly yes. In example: path of length 3 (3 vertices: 1-2-3). This tree is odd sized (3). Remove vertex 2: remaining vertices 1 and 3, which are not connected (no edge), so no perfect matching. Remove vertex 1: remaining vertices 2-3, an edge, perfect matching exists. Remove vertex 3: similar. So good count = 2. So multiple vertices can be good.
We need to compute this count for many subtrees.
Idea: Use DP that for each node v computes:
- dp[v] = size of subtree (maybe parity needed)
- For even-sized subtrees: a boolean perfect[v] indicating if subtree(v) has perfect matching.
- For odd-sized subtrees: count good[v] = number of vertices x in subtree(v) such that subtree(v){x} has perfect matching.
But we also need to compute for odd-sized subtrees the count of such