We need to solve a problem: given a graph with n vertices, m edges (undirected, possibly loops, multiple edges). Each edge is labeled either 'S' (Elf) or 'M' (Santa). We need to select a subset of edges to keep (clear) such that:
-
The subgraph formed is a spanning forest? Actually condition: "between any two huts should exist exactly one simple path along the cleared roads". That implies that the cleared edges form a tree (or a forest?) Wait: "between any two huts should exist exactly one simple path" means that for any pair of vertices, there is exactly one simple path using cleared edges. This property is precisely that the subgraph is a tree spanning all vertices. If the graph were disconnected, then between vertices in different components there would be no path, so condition fails. So the cleared subgraph must be a spanning tree (connected and exactly n-1 edges, no cycles). So it must be a spanning tree covering all n vertices. But what about n=1? If n=1, there are no paths between distinct huts, but "between any two huts" with two huts? Since there is only one hut, vacuously? Typically a spanning tree on 1 vertex has 0 edges, and there is exactly one path (trivial? Actually between a vertex and itself, path of length zero maybe? But they likely consider pairs of distinct huts, but we need to be careful. Example 1: n=1, m=2 with loops. Output is 0 (empty set). So they accept a spanning tree with 0 edges (forest with one vertex). So we need a spanning tree: connected, exactly n-1 edges.
-
Santa and Elf must clear the same number of roads. Let k be number of edges selected (which must be n-1). So condition: among selected edges, count of 'M' = count of 'S' = (n-1)/2? Actually they must be equal, so n-1 must be even. If n-1 is odd, it's impossible. But there might be more complex because we could also consider that the tree might have exactly n-1 edges and equal numbers of M and S, so n-1 must be even => n odd. But is that sufficient? Not necessarily; we need to find a spanning tree with exactly (n-1)/2 edges of each type.
But note: we are allowed to choose any subset of edges (not necessarily all edges used) but must form a spanning tree with equal numbers of M and S. If such a tree exists, we output its edges indices.
We must output -1 if impossible.
Constraints: n up to 1000, m up to 100k. So we need to find a spanning tree with exactly a given number of edges of each color.
This is reminiscent of finding a spanning tree with constraints on two edge types. Equivalent to: we have two colors (M and S). Need a spanning tree T such that |T ∩ E_M| = |T ∩ E_S| = (n-1)/2 (if n-1 even). If n-1 odd, impossible. So problem reduces to: can we find a spanning tree with exactly k edges from each set, where k = (n-1)/2? And if yes, output any such tree.
We can treat it as a matroid intersection problem? The spanning tree is a base of the graphic matroid (or of the forest matroid) of size n-1. We need base with exactly k edges from M set and k from S set. This is a matroid parity? Alternatively we can think in terms of linear algebra with two constraints.
Because n is only 1000, m up to 1e5, we could attempt to use a swap-based algorithm: start with any spanning tree (if exists). Then adjust counts by swapping edges while preserving tree structure until the counts are balanced.
Observation: The set of all spanning trees form a matroid, and the property of having a given number of edges from each color is a partition matroid? Actually we want exactly k edges from M, which is not a matroid independence condition but we can treat as a bipartite constraint.
We can use an approach similar to "Minimum Spanning Tree with exact weight" or "Exact spanning tree" but with two types.
We could also try to reduce to a flow or matching problem.
Idea: We need a tree with exactly k M edges and k S edges. Since total edges n-1 = 2k. So essentially we need a spanning tree that is "balanced". This is similar to finding a spanning tree in a bipartite graph where we can treat colors as two sets.
We can try to construct via augmenting paths: start with a tree that has as many M edges as possible? Or we can treat it as a matroid intersection: We have graphic matroid M1 (forests) and a partition matroid M2 that allows at most k edges from M and at most k from S, but we want exactly k from each, so we can combine constraints: we need a common base of size 2k that is independent in both. Actually graphic matroid bases have size n-1. Partition matroid: if we define two partitions: M edges (allow at most k) and S edges (allow at most k). A set of edges that is independent in both matroids would have at most k from each and size at most 2k. But we need exactly size 2k and base in graphic matroid (size n-1 = 2k). So we need a common base of size 2k in the intersection of graphic matroid and partition matroid (with upper bounds). The matroid intersection theorem says we can find a maximum cardinality set that is independent in both matroids. If the maximum size is 2k, then we have a spanning tree that satisfies the upper bounds. But we need exactly k from each, not just at most. However if we have a base (size 2k) that is independent in partition matroid (i.e., at most k from each), then since total is 2k, it must have exactly k from each (provided k is the bound for each). Because if we have at most k from each and total 2k, the only way is exactly k from each (assuming both counts ≤ k, sum=2k, then each must be k). So indeed, a common base of size 2k exists iff there is a spanning tree with at most k edges from M and at most k from S, which automatically gives exactly k each because total is 2k. But wait: the partition matroid upper bound is at most k from M and at most k from S. If we have a spanning tree with at most k M and at most k S, and total edges 2k, then the counts are exactly k each. So we need to find a spanning tree that respects these upper bounds. That is a matroid intersection problem: maximum size set independent in both matroids. Since we require size exactly n-1, we need to check if the maximum intersection size is n-1.
Thus we can use a matroid intersection algorithm for graphic matroid and partition matroid. The standard algorithm uses augmenting paths and runs in O(r * m * α) where r is rank (n-1) which is up to 999, m up to 1e5, so maybe 1e8 operations, might be borderline but could work with optimizations. But perhaps there is a simpler method.
Alternative approach: treat as a network flow: we can consider building a tree and enforce exactly k M edges. This is similar to finding a spanning tree with a fixed number of edges from a specified set. There is a known technique using Kirchhoff's matrix tree theorem? But that would be counting, not constructing.
Another approach: Use a randomized algorithm? Probably not.
Maybe we can think in terms of exchange: start with any spanning tree T (if exists). If T already has exactly k M edges, done. If not, we need to swap edges to adjust count. Let x = number of M edges in T. We need x = k. If x > k, we need to replace some M edges with S edges, while keeping tree. If x < k, we need to replace some S edges with M edges.
We can try to find a sequence of edge swaps. This is reminiscent of the matroid basis exchange property: For any two bases B1, B2, you can transform B1 to B2 by a sequence of exchanges. However we need to adjust count.
We could try to compute a maximum spanning tree with respect to weights that encourage balance? But we need exact count.
Maybe we can use a reduction to a bipartite matching problem? Consider constructing a tree by selecting k M edges and k S edges. The condition of being a tree means that the selected edges must connect all vertices and be acyclic. Could be phrased as: we need to select a spanning tree such that the number of M edges is exactly k.
This is a classic problem: "Minimum spanning tree with a given number of edges from a set" is NP-hard? Actually there is a result: the "minimum spanning tree with a given number of edges of each type" might be reducible to matroid intersection, which is polynomial. Indeed, finding a spanning tree with a prescribed number of edges from each color is a matroid intersection as described. So polynomial.
But constraints are moderate; maybe we can use a simpler method: transform to a flow problem via matroid parity? There is also the approach of using linear programming on the spanning tree polytope? Not practical.
Let's think about matroid intersection more concretely.
Matroid M1: graphic matroid over edges, independent sets are forests. Its rank is n - c, where c is number of components. We need a spanning tree (so connected graph, c=1, rank n-1). So we need a base (max independent set) of size n-1 that also is independent in the partition matroid M2 (which allows at most k edges from M and at most k from S). M2's rank is 2k = n-1 (since each part capacity k, total capacity 2k). So M2's maximum independent set size is n-1. So we are looking for a common base.
Matroid intersection algorithm: Given two matroids, we can find a maximum cardinality set that is independent in both. The algorithm constructs an exchange graph and finds augmenting paths. It runs in O(r * (m + r * n)) maybe. For graphic matroid, we need to be able to determine for a given set I (independent in both) and edges e not in I, the circuits formed when adding e to each matroid. For graphic matroid, adding e to a forest creates a unique cycle (if its endpoints are already connected). For partition matroid, adding e to I (which respects capacity constraints) might violate capacity if the part is already full. So the exchange graph is directed and we look for augmenting paths.
Standard algorithm for matroid intersection (based on augmenting paths) is O(r * m * (time to find exchange graph)). Since r = O(n) = 1000, m = 100k, r*m = 1e8, which may be okay in C++ with good implementation, but we need to be careful about cycles detection and building graph each iteration.
We could implement this. But maybe there is a simpler way using Union-Find and flows.
Alternative perspective: We need to find a spanning tree where exactly k edges are M. This is like selecting k M-edges and k S-edges such that they form a spanning tree. Equivalent to: find a set A of M edges of size k, and a set B of S edges of size k, such that A ∪ B is a spanning tree. The tree must be connected and acyclic. So we could try to first pick k M edges that form a forest (since tree part), and then add S edges to complete tree. The M edges must not create cycles, and similarly total.
One approach: Use a reduction to a flow or bipartite matching? Consider building a tree by contracting components? Not obvious.
Another idea: Since the constraints are not huge, we could do a randomized approach: assign weights to edges, with M edges weight 0? Not exact.
We might consider using the fact that we just need to output any such tree, not the minimum weight. So we could treat it as a constraint satisfaction problem. Maybe we can use a simple greedy with backtracking? n=1000, impossible.
Let's think about necessary conditions:
-
Graph must be connected (otherwise no spanning tree). So if original graph is not connected, answer -1 (unless n=1? Actually n=1 trivially connected). So check connectivity first? But even if graph is connected, there may not exist balanced spanning tree.
-
n must be odd (since n-1 even). If n even, answer -1 immediately.
But these are necessary not sufficient.
Now, if n odd, we need a spanning tree with exactly (n-1)/2 edges of each type.
Consider treating M edges as red, S as blue. We need a spanning tree with equal red and blue.
We can think about adjusting: start from any spanning tree (use Kruskal). Count red edges. If red = k, done. If red > k, we need to replace some red edges with blue ones. Each replacement: pick a red edge e in tree, remove it, tree splits into two components. We need a blue edge that connects these two components (i.e., a blue edge crossing the cut) to reconnect and keep tree. After replacement, red count decreases by 1, blue increases by 1. So we need to find a sequence of such swaps to achieve balance.
Similarly if red < k, we need to swap blue edges for red edges.
Thus we need to find if we can adjust the tree's color composition via such exchanges. This is similar to having a basis (tree) and exchanging edges of different colors.
We can try to formulate a bipartite graph of exchangeable edges. Essentially, we need to know for each red edge in tree, if there exists a blue edge outside that can replace it (i.e., that forms a cycle with the tree that contains that red edge and some blue edge not in tree, such that when we swap, the blue edge is added and red removed, the tree remains). Actually any blue edge not in tree that connects two vertices in the tree creates a cycle; we can remove any red edge on that cycle to increase blue count by 1 and decrease red count by 1. So if there exists a blue edge outside that forms a cycle containing at least one red tree edge, we can perform a swap.
Similarly, for increasing red count, we need a red edge outside that forms a cycle containing at least one blue tree edge.
Thus, if we have an excess of red, we need to find a sequence of swaps that reduces red count. This is similar to performing augmentations along alternating paths. This is essentially the matroid intersection algorithm but specialized.
We could implement a BFS/DFS to find an augmenting path that changes the color counts. The matroid intersection algorithm for the two matroids would do exactly that: find a sequence of exchanges to increase the size of the intersection (which is independent in both) until maximum. But our initial set I is empty? Actually we want to find a base that is independent in both, but we start with a set that is independent in both (maybe empty). Then we augment to increase size while maintaining independence in both. However, we need to reach size n-1. However, in this case, the partition matroid constraints are upper bounds (k each). But note that during the augmentation we also must respect that the set never exceeds capacity for each color. So we need to start with empty set, then add edges as long as they don't violate capacities or create cycles. But we need to add edges up to size 2k. But at each step we might need to exchange.
However, there is a known simpler algorithm for spanning tree with exact degree constraints? Possibly we can use a flow-based construction: treat the tree as having exactly k red edges; we can use a technique of "minimum spanning tree with limited red edges" by assigning weights 0 to red, 1 to blue (or vice versa) and then find MST with exactly k red edges? This is similar to the problem of finding a minimum spanning tree with a fixed number of edges of a certain type, which can be solved using a parametric search or Lagrange multipliers? Typically, if we assign weight w to red edges and weight 1-w to blue edges and vary w, the MST weight changes piecewise linearly as function of w. The number of red edges in the MST is monotonic in w. So we can binary search on w to get a MST with exactly k red edges. But this works for MST with linear weights; here we don't care about weight, we just need any spanning tree with exactly k red edges. So we can assign arbitrary weights to edges: e.g., give red edges weight 0 and blue edges weight 1. Then the minimum spanning tree will minimize total weight, i.e., prefer red edges. So the MST will have as many red edges as possible (subject to connectivity). Similarly, if we give red edges weight 1 and blue weight 0, the MST will have as many blue as possible. So the number of red edges in MST can vary between a minimum and maximum possible among spanning trees. If k lies between these bounds inclusive, there exists a spanning tree with exactly k red edges. Moreover, by adjusting weights via a parameter, we can find one.
Specifically, consider assigning weight = (1, 0) for (red, blue) to get max red? Actually if we give red weight 0, blue weight 1, then MST minimizes total weight, so it picks as many red as possible, giving maximum number of red edges. Conversely, red weight 1, blue weight 0 gives minimum number of red edges. So we can compute the minimum possible number of red edges (R_min) and maximum possible (R_max) in any spanning tree. If k is not between R_min and R_max, impossible. If it is, there exists a spanning tree with exactly k red edges. Moreover, we can find one by parametric MST: assign weight λ to red edges, 0 to blue (or vice versa) and vary λ. Alternatively, we can use a more constructive method: find a spanning tree with exactly k red edges by starting from a tree with many red edges and swapping edges to reduce red count gradually.
The parametric approach: For each spanning tree, total weight = λ * (#red) + 0*(#blue) = λ * (#red). As λ varies, the MST changes at points where the relative order of edges changes. However, the number of red edges in MST is a monotonic function of λ (nonincreasing as λ increases, because red becomes more expensive). So we could binary search λ (real) and compute MST with standard Kruskal sorting by weight (with ties broken appropriately) to get a tree with a certain number of red edges. But ties can cause multiple possible trees, but we can control tie-breaking to favor red or blue to push the count. This is standard technique for "minimum spanning tree with a constraint on number of edges of a certain type". We can compute two trees: one with max red (by sorting: red first then blue) and one with min red (blue first then red). That gives R_max and R_min. Then if k is between, we can gradually adjust.
We can use an algorithm that, given any two spanning trees T1 (with R_max red) and T2 (with R_min red), we can transform one into the other via edge exchanges that change red count by at most 1 each step, and each intermediate is a spanning tree. This is because the set of spanning trees forms a matroid basis graph which is connected under basis exchange; moreover, if we restrict to exchanges that change the red count by 1 (swap a red for a blue), we can likely get from T1 to T2 and thereby cover all counts in between. So if k is in between, we can find a tree with exactly k red by starting from T1 and repeatedly swap a red edge for a blue edge until red count = k.
Thus, we need to implement a method to perform such swaps. This is exactly the basis exchange approach.
So plan:
-
Check connectivity of original graph (ignoring edge colors). If not connected, output -1 (unless n=1? but if n>1 and disconnected, impossible). Use union-find to test.
-
If n even, output -1 (since n-1 odd -> cannot have equal numbers). But careful: if n=1, n-1=0 even? 0 is even, so equal numbers (0 and 0) is possible. For n=1, n-1=0, that's even. So condition: n-1 must be even => (n-1) mod 2 =0 => n odd. So if n > 1 and even, output -1.
-
Let k = (n-1)/2 (integer). For n=1, k=0.
-
Compute maximum possible number of red edges (say red = M edges) in a spanning tree. We'll denote M as 'M' edges (Santa). We'll call them type M.
We need to compute R_max (max #M in any spanning tree) and R_min (min #M). Actually we need to see if k lies between R_min and R_max. If yes, we can find a spanning tree with exactly k M edges.
How to compute R_max? Use Kruskal-like algorithm that always picks M edges before S edges when both are available, to maximize M count. But careful: The goal is to maximize number of M edges in a spanning tree. That's a matroid optimization problem: we have a graphic matroid, we want a basis that maximizes the number of elements from a set (M). This is a matroid maximum-weight independent set problem, where we assign weight 1 to M edges and 0 to S edges. The greedy algorithm (sort by weight descending) indeed gives the maximum-weight basis (by matroid property). So we can sort edges: M edges first, then S edges (any order within), and run Kruskal. That yields a spanning tree with maximum possible number of M edges (R_max). Similarly, to minimize number of M edges, assign weight 0 to M and 1 to S? Actually to minimize M, we want to prefer S edges. So we can sort with S edges first, then M edges. That yields a spanning tree with minimum M (R_min). However, note that there may be multiple max-weight bases if ties, but the greedy algorithm gives some maximum-weight basis. Since weights are only 0/1, the greedy algorithm will pick as many M as possible, but is it guaranteed to give the maximum count? Yes, because it's a matroid and greedy works for maximizing weight with nonnegative weights. So correct.
We'll compute R_max and R_min via two Kruskal runs.
But need to ensure connectivity: If the graph is connected, any maximal forest will be spanning. But the greedy algorithm might produce a spanning tree only if we run Kruskal until we have n-1 edges. But if the graph is connected, Kruskal will indeed yield a spanning tree because we will have enough edges.
Edge cases: If the graph is connected, Kruskal will collect n-1 edges. If not connected, we already output -1. So fine.
Thus compute:
-
R_max: sort edges: all M edges (with some order) then S edges. But there may be multiple edges with same color; any order works. Then run Kruskal: pick edge if it connects different components, ignore if forms cycle. Count how many M edges selected.
-
R_min: sort: S edges first, then M edges. Count M edges selected.
But careful: for R_min, we want to minimize number of M edges. Equivalent to maximize number of S edges. Since total edges in tree is fixed n-1, minimizing M is equivalent to maximizing S. So greedy with S first gives max S, thus min M. So yes.
Now, if k is between R_min and R_max inclusive, then there exists a spanning tree with exactly k M edges. Otherwise, output -1.
Now we need to construct such a tree.
Construction method:
We can start from the tree with R_max M edges (call T_max). If R_max == k, output T_max. Else we need to reduce the number of M edges by swapping M edges with S edges until count = k.
We can similarly start from T_min if R_min == k. But R_max >= k >= R_min, so we can go from T_max downwards.
So we need a procedure to replace an M edge with an S edge while keeping the tree.
General step: We have a spanning tree T. We want to decrease #M by 1. Find an M edge e in T and an S edge f not in T such that f connects the two components of T \ {e} (i.e., f forms a cycle with T containing e). Then replace e with f, resulting new tree T' with one less M and one more S.
Similarly, if we needed to increase #M (starting from T_min), we would look for an S edge in T and an M edge not in T to swap.
Thus, we need to be able to find such swaps efficiently. We need to perform up to (R_max - k) swaps, which could be up to n-1 (1000). Each swap might be found by scanning edges? Could be O(m) per swap => O(n*m) = 1e8, acceptable? Possibly.
But we need to ensure that we can always find a swap if R_max > k and we haven't reached k yet. Is it guaranteed that if current #M > k, there exists an M edge that can be swapped with an S edge? Not necessarily; maybe all M edges in the current tree are "forced": every S edge not in tree, when added, creates a cycle that contains only S edges? Actually if we want to replace an M with an S, we need an S edge that connects the two components after removing an M edge. That S edge may not exist. But if the current #M > R_min, then there exists some M edge that can be swapped? Actually by matroid basis exchange property and the fact that we can transform between any two bases via exchanges, but those exchanges may change the M count by more than 1? However, the basis exchange graph is connected, but the steps may involve swapping edges of same color? To reduce M count, we need an exchange that swaps an M for an S. If we are at a basis with #M > R_min, there must exist a basis with #M = #M - 1? Not necessarily; the set of possible #M among bases might not be contiguous? I suspect it is contiguous. For matroids, the set of possible sizes of a set of a particular type in bases is a contiguous interval. This is a property: For a matroid, the set of possible numbers of elements from a given set that a basis can have forms a consecutive integer interval. This is known as the "basis exchange property" or "strong exchange property". For graphic matroid, I think it's true. Because we can adjust by one using symmetric exchange? There is a theorem: For any matroid, the set of possible sizes of intersection of a basis with a fixed subset is a contiguous interval. This follows from matroid basis exchange and the fact that we can increment/decrement by one. Actually, it's a known result: Given a matroid and a subset X of the ground set, the set { |B ∩ X| : B is a basis } is an interval [min, max] of integers. This is true because of the matroid parity property? I recall it's true for matroids (maybe a consequence of the exchange property). For example, for bipartite matching (which is a transversal matroid) it's true. For graphic matroid, it should be true as well. So if R_max > R_min, there exists a basis with any count between. Moreover, we can achieve each step by swapping an edge of one color for an edge of the other color. So we can indeed reduce M count by 1 while keeping a tree.
Thus we can implement a loop: while #M > k, find a pair (e in T, M edge) and (f not in T, S edge) such that f replaces e. Then update T.
We need an efficient way to find such a swap. Since n <= 1000, m <= 100k, we could for each M edge in T, check if there exists an S edge outside that connects the two components after removing e. We can precompute the tree and for each non-tree edge (S or M), we can identify the tree edges on the unique path between its endpoints (the cycle). Then if we want to replace an M edge with an S edge, we need an S edge whose cycle includes that M edge. So for each S edge not in T, it gives a set of tree edges that can be swapped out if we add that S edge. Particularly, if we want to replace an M tree edge with that S edge, we need that M edge to be on the path. So we can maintain for each tree edge e, a list of candidate non-tree S edges that could replace e (i.e., whose fundamental cycle includes e). Then to reduce M count, we pick an M edge e that has at least one candidate S edge f. Then perform swap: add f to T, remove e. After swapping, the tree changes, so the candidate lists need to be updated.
We can recompute from scratch each iteration O(m) time; with up to 1000 iterations, O(n*m) = 1e8, which might be okay. But we can attempt to be more efficient: each iteration we could find a swap by scanning non-tree edges until we find an S edge whose path contains at least one M edge. Then we can choose any such M edge to swap. However, after swapping, the tree changes; we would need to update data structures. But recomputing from scratch each time might be simpler given constraints. 1e8 operations with simple loops in C++ is borderline but possibly acceptable (since 1e8 is like 0.1 sec? Actually typical C++ can do ~1e8 operations in a few seconds, but with graph operations (DFS for each edge to find path) might be slower. However, we can do better: we can use LCA to query path edges quickly. n=1000, so we can precompute parent and depth each iteration and then for each non-tree edge (u,v) we can find the path edges in O(depth) ~ O(n) by climbing. So per iteration scanning all m edges would be O(m * n) = 1e8 (since 1000 * 100k = 1e8) but that's per iteration? That would be 1e8 * iterations (up to 1000) = 1e11 too large. So we need smarter.
Actually we can reduce: We only need to find a single swap per iteration. We could do a BFS/DFS from one side to find an augmenting path, like in matroid intersection. But maybe we can implement the standard matroid intersection algorithm, which is O(r * m * α). r = 1000, m = 100k => 1e8 operations; each operation might be simple union-find or DFS. That's likely acceptable within time limit (2 sec?) maybe with careful optimization. But we can also implement the simpler swap approach but with more efficient data structures: we can maintain for each non-tree edge the set of tree edges on its fundamental cycle using a bitset (since n=1000, we can have a bitset of length n-1 (max 999) per edge. That's 100k * 1000 bits = 100 million bits = 12.5 MB, which is manageable. Actually we can store for each non-tree edge a bitset indicating which tree edges are on its fundamental cycle. Then to find a swap, we need to find an M tree edge e such that there exists an S non-tree edge f with bit set for e. We can maintain for each tree edge e a list of candidate non-tree edges (or just a count). Then when we swap, we need to update the tree and recompute bitsets for many non-tree edges. That could be heavy.
Alternatively, we could implement matroid intersection directly. Let's design that.
Standard matroid intersection algorithm (for maximum cardinality common independent set):
Given matroids M1 and M2 on ground set E, we want max |I| s.t. I ∈ I1 ∩ I2.
Algorithm:
-
Start with I = ∅.
-
While true:
a. Build exchange graph D(I):
For each e ∈ E \ I:
if I ∪ {e} ∈ I1, add directed edge from e to some f? Actually the exchange graph is defined on vertices E \ I ∪ I (maybe). Standard: The exchange graph for augmenting path has two sets: left part (elements not in I) that can be added to I with respect to one matroid, and right part (elements in I) that can be removed. We construct a directed bipartite graph (X, Y) where X = I, Y = E \ I. There are arcs:
For y ∈ Y, if I + y ∈ I1, then y is a source (can be added to I without violating M1? Actually we need to consider both matroids; the augmenting path approach is:
- Compute S = { y ∈ E \ I : I + y ∈ I1 } (i.e., adding y doesn't violate M1)
- Compute T = { y ∈ E \ I : I + y ∈ I2 }
- For each x ∈ I, and y ∈ E \ I, add directed edge y -> x if (I - x + y) ∈ I1 (i.e., y can replace x in M1)
- For each x ∈ I, and y ∈ E \ I, add directed edge x -> y if (I - x + y) ∈ I2 (i.e., y can replace x in M2)
Then find a shortest path (in terms of edges) from S to T. If exists, augment: I = I Δ P (symmetric difference). This increases |I| by 1.
The algorithm runs in O(r * (|E| + r) * query), where each query checks independence in M1 and M2. For graphic matroid, independence check is: adding an edge to a forest (current I) and checking if it creates a cycle – can be done with union-find (since I is a forest). But note that I is a forest (since it's independent in graphic matroid). So we can maintain a DSU for I to quickly check cycles. For partition matroid, independence is simply: I has at most k edges of each color. So we can track counts.
We need to run this algorithm until I reaches size n-1 (if possible). But we also need to guarantee that the final I is a spanning tree (i.e., connected). Actually, maximum common independent set size could be less than n-1 if graph is not connected? But we already checked connectivity, so graphic matroid's maximum independent set size is n-1 (since rank = n-1). However, partition matroid might restrict that we cannot have more than k edges of each color, so total max size = 2k = n-1, exactly the rank. So if the graph is connected, the maximum common independent set size is either n-1 (if possible) or less. The algorithm will find maximum size; if it's less than n-1, then impossible. So we can just run the matroid intersection to get a max common independent set I. If |I| = n-1, then we have a spanning tree that satisfies the capacities (and hence equal counts). If not, output -1.
This approach is straightforward to implement: we start with empty set, then repeatedly augment until we cannot. Each augmentation increases size by 1. So we need up to n-1 augmentations (1000). Each augmentation we need to build the exchange graph and find a shortest path. Building the graph requires for each y ∈ E\I and each x ∈ I, we need to check if I - x + y ∈ M1 and M2. That's O(|I| * |E\I|) = O(r * m) per augmentation, which is about 1000 * 100k = 1e8 per augmentation? That would be too much: 1e8 per iteration, times 1000 iterations = 1e11. So we need to optimize.
But we can reduce using properties of the matroids. For graphic matroid, the condition (I - x + y) ∈ M1 means that adding y to I{x} does not create a cycle. Equivalently, y does not create a cycle in I, or if it does, the cycle must include x, and removing x breaks it. More precisely, given current I (a forest), if y connects two vertices that are already connected in I, then adding y would create a cycle. For I - x + y to be a forest, we need that either (a) adding y to I does not create a cycle (i.e., y connects two different components of I), then I - x + y is a forest regardless of x? Actually if I + y is already independent (i.e., y connects two components), then for any x, I - x + y is also independent because I - x is a forest with possibly two components? Wait, I - x might break connectivity, but adding y could still create a cycle? Need careful. Let's reason.
I is a forest (acyclic). We consider swapping x ∈ I with y ∉ I. We want I' = I \ {x} ∪ {y} to be a forest. Conditions:
-
If y connects two vertices that are already in the same component of I, then adding y creates a cycle. For I' to be acyclic, we must ensure that the cycle is broken by removing x. That is, the unique cycle formed by adding y to I must contain x. Because if we remove x from that cycle, the cycle is broken. So condition: y creates a cycle in I, and x lies on that cycle.
-
If y connects two different components of I, then adding y to I does not create a cycle; I ∪ {y} is still a forest (since it connects two trees). In that case, I' = I \ {x} ∪ {y} might still be a forest if after removing x, the graph remains acyclic. But careful: if we remove x, I \ {x} becomes a forest with possibly two components (if x was a bridge). Adding y might reconnect them, but it could also create a cycle if y connects vertices within the same component of I \ {x}. However, since y originally connected two different components of I, after removing x, these two vertices might become in the same component? Let's analyze.
Let I be a forest. Let C1 and C2 be the components of I that contain the endpoints of y. If C1 ≠ C2, then y is a bridge between them in I ∪ {y} (still acyclic). Now consider removing x from I. If x is not in C1 or C2? Actually x could be anywhere. After removing x, the components might split further. But the endpoints of y are still in possibly different components? They could become in the same component if x was on the unique path connecting them? But initially C1 and C2 are different; there is no path between them in I. Removing x cannot create a connection between C1 and C2 because they were separate; removing an edge only increases number of components, not merges them. So after removing x, the vertices in C1 and C2 remain in separate components (unless x was the only edge connecting parts within C1? But C1 and C2 are distinct components; they have no edges between them. Removing x from C1 does not affect connectivity between C1 and C2. So the endpoints of y are still in different components of I \ {x}. Therefore, adding y to I \ {x} will not create a cycle. So I' is a forest.
Thus, condition for I' ∈ M1 (graphic) is: either (I ∪ {y}) is acyclic (i.e., endpoints of y in different components of I) OR (if adding y creates a cycle, then x must be on that unique cycle). So we can compute:
-
For each y ∉ I, if its endpoints are in different components of I (using DSU on I), then I + y is independent, so for any x ∈ I, I - x + y is independent? As argued, yes. So then from perspective of exchange graph, for such y, we have arcs y -> x? Wait the arcs are defined differently: For x ∈ I, y ∈ E\I, we have arc y -> x if I - x + y ∈ M1. So if I + y is independent (i.e., endpoints in different components), then for any x, I - x + y is independent (since removal of x doesn't create cycle). So we would have arcs from y to every x ∈ I. That's many arcs, but we can treat it specially.
-
If y's endpoints are in same component of I (so adding y creates a cycle), then I - x + y is independent iff x lies on the unique cycle in I formed by y. That cycle is the path in I between its endpoints. So only those x on that path satisfy the condition.
Thus, we can compute these arcs efficiently if we can, for each y, determine: the set of x ∈ I that are on the tree path between its endpoints (if any) or all x if y connects different components.
Similarly, for partition matroid M2: I is independent if it has at most k edges of each color. Let cap_M = k, cap_S = k. For a given I, we maintain counts cnt_M, cnt_S. Then:
-
For y ∉ I, I + y ∈ M2 iff adding y does not exceed capacity for its color. So S set (sources) are y such that I + y ∈ M2.
-
For x ∈ I and y ∉ I, I - x + y ∈ M2 if: either color(y) == color(x) (then counts unchanged) OR color(y) different, then after removal of x and addition of y, the count for color(x) decreases by 1 and color(y) increases by 1, so we need new counts still ≤ k. So condition: if col(y) == col(x): always OK (since counts same). If col(y) != col(x): then cnt_col(y) + 1 ≤ k and cnt_col(x) - 1 ≥ 0 (but removal always reduces, so only need cnt_col(y) < k). Actually we need cnt_col(y) < k (since after addition it becomes cnt_col(y)+1 ≤ k) and cnt_col(x) > 0 obviously because x is present. So condition: (col(y) != col(x)) => cnt_col(y) < k.
So for arcs from x to y (i.e., condition for I - x + y ∈ M2), we have: if col(y)==col(x) always true; else cnt_col(y) < k.
Similarly, arcs from y to x: that's for M1 condition as above, not M2. Actually the exchange graph uses two types of arcs: from y (outside) to x (inside) based on M1 (graphic), and from x (inside) to y (outside) based on M2. Also we have sources (y such that I+y ∈ M1) and sinks (y such that I+y ∈ M2). Wait the standard algorithm:
We define directed graph D(I) with vertex set = I ∪ (E\I). Add arcs:
- For y ∈ E\I, x ∈ I: add arc y -> x if I - x + y ∈ M1.
- For x ∈ I, y ∈ E\I: add arc x -> y if I - x + y ∈ M2.
Then we find a shortest path from any y1 in S = { y ∈ E\I : I + y ∈ M1 } to any y2 in T = { y ∈ E\I : I + y ∈ M2 }. After finding such a path (alternating outside-inside-outside...), we augment by taking symmetric difference I Δ P.
So we need to compute S and T quickly.
S: y ∉ I such that I + y ∈ M1, i.e., y connects two different components of I (i.e., its endpoints are in different DSU components). That's easy: we can maintain a DSU over vertices for the current forest I. So for each y, we can check if find(u) != find(v).
T: y ∉ I such that I + y ∈ M2, i.e., adding y does not exceed capacity for its color: for y color c, we need cnt_c < k (since we have capacity k). Because I already has cnt_c edges of color c, and we want to add another of same color. So condition: cnt_c < k.
Now arcs:
- y -> x (based on M1): as described, condition: either (I + y is independent) OR (x lies on the unique cycle formed by y). Since I is a forest, we can compute for each y (outside) the set of x that satisfy. However, building all arcs explicitly could be O(|I| * |E\I|) which is large. We need to find a shortest augmenting path without explicitly building all arcs. We can BFS/DFS on the implicit graph.
We need to perform BFS from all S nodes, exploring neighbors using the arcs, until we hit a T node. Since the graph is bipartite and we only care about existence of a path, we can BFS on the state (node) but we need to generate neighbors efficiently.
We can approach BFS by alternating between outside and inside nodes. Starting from an outside node y (in S), we can go to inside nodes x via y->x arcs (M1 condition). Then from an inside node x, we can go to outside nodes y via x->y arcs (M2 condition). So BFS will need to enumerate:
- From an outside node y: all inside nodes x such that I - x + y ∈ M1.
- From an inside node x: all outside nodes y such that I - x + y ∈ M2.
The second is easier: For a given x ∈ I, the condition for M2 is: y ∉ I, and (col(y)==col(x) or cnt_col(y) < k). So we can precompute sets of outside edges by color. So for a given x, we can iterate over all outside edges of the same color (since always allowed) and also outside edges of opposite color if cnt of that color < k. But that could be many: there are up to 1e5 edges, and we may visit many inside nodes during BFS, leading to O(m * r) again. However, we can optimize by noting that from an inside node x, the allowed outside nodes are essentially all outside edges except those that would violate capacity. But the capacity condition only restricts opposite color edges when its count already equals k. Since we only augment when we haven't yet reached full capacity? Actually during the algorithm, I's size increases from 0 to n-1. At the start, counts are low. As we progress, some color may reach k. When cnt_c = k, we cannot add more edges of that color, so T set excludes edges of that color (since I+y would violate M2). Also for arcs x->y, if col(y) != col(x) and cnt_col(y) == k, then that arc is not present. But if col(y)==col(x), it's always allowed even if cnt_col(y) = k? Wait if cnt_col(y) = k and col(y)==col(x), then I - x + y would have same counts (since we remove one of that color and add one of same color), so count remains k, which is allowed. So from an inside x of color c, we can go to any outside y of the same color c, regardless of cnt_c. For opposite color d, we can go only if cnt_d < k.
So from a given x, we might need to iterate over all outside edges of the same color, and if cnt of opposite < k, also all outside edges of opposite color. That's O(m) per x, which is too many if BFS visits many x.
We need a more clever approach. Since n is only 1000, we might try to use the fact that the tree size is at most 999. Possibly we can afford O(n * m) per augmentation? But we have up to 1000 augmentations, so O(n * m * r) = 1e11 not feasible.
We need to reduce complexity. Maybe we can use the fact that the graphic matroid condition for y->x can be represented in terms of connectivity: for y outside, if its endpoints are in different components, then it connects to all x ∈ I. That's O(r) per y, which is also many.
But maybe we can find augmenting paths more efficiently by constructing an auxiliary graph with vertices as components? There is known faster matroid intersection algorithms for graphic matroid and partition matroid, perhaps using flow or contraction? Actually we can use a more specialized algorithm.
Alternative: Since the partition matroid is simple, we can transform the problem into a flow on the tree? Another idea: Model as finding a spanning tree with exactly k M edges. This can be solved via a reduction to finding a feasible flow in a bipartite graph? Not exactly.
Maybe we can use a simpler constructive approach: start from a tree with max M (or min M) and then perform swaps using a systematic method to adjust count by 1. We can use the concept of "exchangeability graph" focusing on edges that are candidates.
Let's think of the swapping approach directly: We have a spanning tree T. We want to replace one M edge with an S edge. For each S edge f not in T, if we add f to T, it creates a cycle C. If C contains at least one M edge, we can remove any such M edge to get a new tree with one more S and one less M. So to reduce M count, we need to find an S edge f whose cycle contains an M edge. Then we can swap. Similarly, to increase M count, we need an M edge f whose cycle contains an S edge.
Thus, we can maintain the tree and for each non-tree edge, we can quickly determine if its cycle contains an edge of a desired color. To find a swap, we could iterate over all non-tree edges until we find an S edge whose cycle contains an M edge. Then we perform the swap. Updating after swap: we remove an M edge e and add an S edge f. The tree changes, so the cycles for other non-tree edges also change. However, we could recompute from scratch after each swap. The number of swaps needed is at most (R_max - k) <= (n-1) <= 999. So we could perform up to 999 swaps. For each swap, we might need to recompute something like for each non-tree edge, find its cycle. If we do that from scratch each time, each time we would need to process all non-tree edges (up to m) and for each, compute the path in the tree between its endpoints to see if it contains an M edge. If we use LCA/preprocessing per tree, we can answer path queries in O(log n) per edge after O(n) preprocessing. Since n is only 1000, we could even do O(n) per edge via DFS. Let's evaluate: For each swap, we could rebuild the tree structure (adjacency list) and then for each non-tree edge, we need to check if its path in tree contains an M edge. To do that, we can precompute parent and depth arrays, and then for each non-tree edge (u,v), we can walk up from u and v to LCA, checking edges along the way for M. Since tree depth ≤ n, worst-case O(n) per edge. So each swap would cost O(m * n) = 100k * 1000 = 1e8 operations. Over 1000 swaps, that's 1e11, too high.
But we can improve: we can, for each non-tree edge, store the set of tree edges on its fundamental cycle using bitsets. Since n=1000, the tree has at most 999 edges. So each non-tree edge can have a bitset of length 999 indicating which tree edges are on its cycle. Then to check if there is an M edge on that cycle, we can AND with a bitset of M edges in the tree. This is efficient: we can represent bitsets as 16 64-bit integers (since 999/64 ≈ 16). Then per non-tree edge we can test in O(16) operations. So building these bitsets initially would require computing the cycle for each non-tree edge once per tree configuration. But when the tree changes (swap), we need to update these bitsets for all non-tree edges. That could be heavy: after each swap, the tree changes; recomputing bitsets for all non-tree edges from scratch would be O(m * n) again per swap, which is too heavy.
But perhaps we can update only a subset? When we swap e (removed) and f (added), the tree structure changes. The fundamental cycles for other non-tree edges may change. However, we can possibly update using dynamic tree data structures (link-cut tree) to maintain path information. But that's complex.
Given the constraints, maybe the matroid intersection algorithm is simpler to implement with acceptable performance if we optimize using the structural properties of graphic matroid. Actually the standard matroid intersection algorithm can be implemented in O(r * m * α) where each independence test is O(α) if we use union-find cleverly. But we need to build the exchange graph quickly. There is a known algorithm for matroid intersection specifically for graphic matroid that runs in O(r * m * log n) maybe. But we can try to implement the BFS using an approach that leverages the tree structure.
Let's analyze the exchange graph more concretely. Our matroids:
- M1: graphic. I is a forest (since we maintain independence). We'll have a spanning forest; initially empty; after augmentations, I will be a forest but not necessarily spanning until final step. At intermediate stages, I is a forest (acyclic) with size < n-1. It may not be connected (since we are building a spanning tree, but before completion, it's a forest). However, we need final I to be a spanning tree (connected). But the algorithm ensures that we grow a common independent set, but we don't enforce connectivity until size n-1. At intermediate steps, I is a forest (independent in M1) and also respects color capacities (M2). So it's a forest that may have several components. That's okay.
We want to increase |I| by 1 each augmentation, eventually reaching size n-1. So we need to find an augmenting path.
The exchange graph can be built more efficiently using the structure of the graphic matroid.
Recall that for graphic matroid, given I (forest), for any edge y ∉ I, the set of x ∈ I such that I - x + y ∈ M1 is:
-
If y connects two different components of I, then all x ∈ I satisfy? Actually as argued, if y connects two different components, then I - x + y is independent for any x? Let's double-check: I is a forest. If y's endpoints are in different components, then I + y is still a forest (no cycle). Removing any x from I gives I - x, which is a forest with possibly an extra component. Adding y to I - x: The endpoints of y are in two components of I - x (since originally they were in different components of I, and removing x can only split components further, but cannot merge them). So they remain in different components, thus adding y does not create a cycle. So yes, for any x ∈ I, I - x + y ∈ M1. So in this case, y has arcs to every x ∈ I.
-
If y's endpoints are in the same component of I, then y creates a cycle C (the unique cycle in I + y). Then I - x + y ∈ M1 iff x ∈ C (i.e., x lies on that cycle). So arcs from y to x exactly for x on that cycle.
Thus, we can compute these arcs efficiently if we can, for each y, either know that it's "bridge" (connects components) and then it connects to all x, or know the set of tree edges on its cycle. Since I is a forest, but may not be connected, we need to consider components.
Now, for arcs x -> y (based on M2), the condition is simple: depends on colors and counts.
Given that |I| is at most 999, we could, for each y, explicitly store the set of x it can go to (maybe as a list). However, number of y is up to 1e5, and each may have up to |I| arcs in the worst case (if y bridges components). That could be huge: if I is small early, it's okay; but as I grows, |I| becomes up to 999, and many y could be bridging? Actually if I is a forest, as it grows, many edges will be within the same component, so they will have limited cycle sets. But some edges may be between components, which would have arcs to all x (size |I|). The number of such edges could be large. For example, when I is near a spanning tree, there are few components; many edges will be within the single component (the tree) and thus have cycles; edges connecting the same component will have cycle size O(n). But edges that connect different components? At the final stages, I is connected (a tree), so there are no edges connecting different components; all non-tree edges are within the same component, so they have arcs only to x on their cycle. So the worst case for arcs might be when I is very sparse (many components). At that time, |I| is small, so the total number of arcs (y->x) might be manageable: if I has size r, then each y either has arcs to at most r (if bridging) or to cycle edges, which also at most r (but typically smaller). So total arcs could be O(m * r) in worst-case (since each y may point to all x if it's bridging). When r ~ 500, m=1e5, that's 5e7 arcs per BFS, which might be high but perhaps still okay if we don't explicitly store them but generate on the fly.
We can attempt to implement BFS without constructing all arcs explicitly. We need to traverse from outside nodes to inside nodes and vice versa.
Observation: The BFS from S nodes (outside y where I+y ∈ M1) to T nodes (outside y where I+y ∈ M2). Since we only need any shortest path, we can BFS level by level.
We can treat the state as either being at an outside node (edge not in I) or inside node (edge in I). But we can also compress the graph.
Another approach: Since the partition matroid is simple, we can transform the problem into a flow on the tree as follows: Suppose we fix a tree T (unknown). The condition that T has exactly k M edges is like selecting a spanning tree with a given number of M edges. This can be modeled as a matroid intersection between graphic matroid and a partition matroid. There is a polynomial algorithm that uses weighted matroid intersection? Actually we can use the fact that we can assign weights to edges: assign weight 1 to M edges, 0 to S edges. Then we want a spanning tree of total weight exactly k. This is a "minimum spanning tree with a fixed sum" problem. This can be solved by a parametric