We need to solve a problem: given an undirected graph with N nodes, M edges, we need to select a set of vertices (quarantine stations) such that every edge has at least one endpoint selected. That's the classical vertex cover problem. However, we have an additional constraint: we can build at most K stations (so we want a vertex cover of size <= K). And we need to output the minimum required number of quarantine stations (i.e., the size of minimum vertex cover) if that minimum is <= K, otherwise "Impossible" if the minimum vertex cover size > K? Wait: The problem says: "the department can build at most K quarantine stations due to the lack of budget. Your task is to calculate whether this objective is possible or not. And if it is possible, you must calculate the minimum required number of quarantine stations." So we need to compute the minimum vertex cover size (since they want the minimum required number) but only if it is <= K; otherwise output "Impossible". However, if the minimum vertex cover size is less than or equal to K, we output that number, not necessarily K? Yes: "calculate the minimum required number of quarantine stations." So we need the minimum vertex cover size, but with the condition that we only answer if it is <= K. If the minimum > K, output "Impossible". So essentially compute the size of a minimum vertex cover; if that size > K, then "Impossible", else that size.
But N up to 3000, M up to 30000, K up to 32. That's interesting: K is small. The problem is likely intended to be solved using a parameterized algorithm for vertex cover with small K. However, we need to compute the minimum size, not just whether there is a cover of size <= K. But since K is small (<=32), we can find the minimum vertex cover exactly using a parameterized algorithm that searches for a cover of size at most some bound, and then binary search on the size up to K. Or we can directly use a branch and bound algorithm to compute the minimum vertex cover size. Because N is 3000, but with M up to 30k, the graph is fairly dense; but K is small, so a typical parameterized algorithm will work in O(2^K * something). However, there's also a polynomial-time algorithm for vertex cover in bipartite graphs? But this graph is general, and minimum vertex cover is NP-hard. But with K <= 32, it's fixed-parameter tractable. The constraints N up to 3000, M up to 30k, and K small suggests that we can use a FPT algorithm with kernelization to reduce the graph, then branch. Since K is only up to 32, and we only need to check if min <= K, and if so find it, we can run a recursive algorithm that tries to find a vertex cover of size at most t, increasing t from 0 to K. But since we also need the exact minimum, we can start from low t and increase until we find a cover. But worst-case t could be K=32, and each branching step might be exponential.
Alternatively, note that the problem might be solvable via reduction to bipartite matching? Actually, the minimum vertex cover in a general graph is NP-hard. However, the constraints N=3000, M=30000, K<=32, so it's like a parameterized problem. There's a well-known O(2^k * (n+m)) algorithm for vertex cover using recursion: pick an edge (u,v), either include u or v. And we can apply kernelization: remove vertices of degree 0, and also if any vertex has degree > k, then it must be included? Wait: For vertex cover of size at most k, if a vertex has degree > k, then it must be in any cover of size <= k. Because if we don't include it, we must include all its neighbors, which are > k, impossible. So we can force include it. That's a reduction rule. Also, if after removing high-degree vertices, the graph has more than k^2 edges? Actually, a known kernel for vertex cover: after applying the rule that vertices with degree > k must be selected, we get a graph with maximum degree <= k. Then if there are more than k^2 vertices? Actually, a graph with maximum degree <= k and a vertex cover of size <= k can have at most k*(k+1) vertices? Let's recall: after forced includes, we can get a kernel of size O(k^2). Standard kernel: remove isolated vertices; then if any vertex has degree > k, include it; else (max degree <= k), if the number of vertices > k^2 + k, then answer NO because each edge must be covered by at most k vertices, but I'm not sure about exact bound. Known kernel: If the graph has a vertex cover of size at most k, then after removing high-degree vertices (forcing), the remaining graph has at most k^2 edges? Actually, there is the Buss kernel: If after including all vertices of degree > k (since they must be in any cover of size <= k), we are left with vertices of degree <= k. If the number of vertices remaining is > k^2 + k, then we can answer NO. But we can also use the rule: If the number of edges > k * (number of vertices) maybe? Let's derive: In a graph with vertex cover size <= k, the remaining independent set (the complement of the cover) can have at most something? Actually, a standard kernel for vertex cover: After removing isolated vertices and forcing vertices of degree > k, if the number of vertices exceeds k^2, then answer NO. Because each vertex not in the cover (i.e., in the independent set) can have at most k edges to the cover (since degree <= k), and the cover has at most k vertices, so maximum number of vertices not in the cover is at most k * k = k^2. So total vertices <= k + k^2. So kernel size O(k^2). And the number of edges <= k * number of vertices (since max degree <= k) so O(k^3). With k <= 32, that's manageable.
However, note: we are not necessarily looking for a cover of size <= k for a given k; we want the minimum size. We can try to find the exact minimum cover size, but we can use the fact that K <= 32 and maybe the minimum is not necessarily <=K, but if it's >K we output Impossible. So we can attempt to compute the minimum vertex cover size exactly if it is <= 32; else we just need to know it's >32. So we can apply kernelization for each attempt with a budget t, but it might be better to directly compute the minimum vertex cover size using an exact algorithm with a branch-and-bound that uses a lower bound (e.g., from maximum matching) and recursion with small depth. Since K is small, we can perform recursion with search tree size bounded by something like 2^K.
Alternatively, we can use the following approach: Since K is at most 32, we can apply a classic FPT algorithm for vertex cover that runs in O(1.2738^k + kn) maybe? But we need to implement it ourselves. However, the simpler method: Use recursion with edge selection and apply reduction rules (degree 0, degree 1, degree > t). For each recursive call with budget t (remaining allowed vertices to pick), we can apply the rules: If no edges remain -> success. If t == 0 and edges remain -> failure. If there is a vertex with degree > t, we must pick it. If there is a vertex of degree 1, we can pick its neighbor (since it's better to pick the neighbor to cover that edge and possibly more). Actually, for vertex cover, if a vertex has degree 1, we can safely pick its neighbor rather than picking the leaf itself? Let's think: For a leaf (degree 1), either pick the leaf or its neighbor. If we pick the neighbor, we cover the edge and maybe cover other edges incident to the neighbor. That is at least as good as picking the leaf because picking the leaf covers only that edge, while picking the neighbor may also cover other edges. However, in an exact minimum cover, we can decide optimally: in the presence of a leaf, there is always a minimum cover that includes the neighbor and not the leaf. Because if a minimum cover includes the leaf, we can replace it with the neighbor and still have a cover (since the neighbor covers the leaf's edge, and any other edges incident to neighbor are also covered; the leaf's other edges none). So we can safely include the neighbor and remove both. So we can apply reduction: if degree 1 vertex exists, pick its neighbor (i.e., include it in the cover) and reduce t by 1, remove that neighbor and all incident edges.
Also, if there is an isolated vertex (degree 0), remove it.
Also, if t is large, we could also apply other reductions like crown reduction, but might be overkill.
Given that K is only up to 32, a straightforward recursion with these reductions should be fine for N=3000, M=30000? Possibly, but the recursion might be too deep if we don't kernelize. However, we can apply kernelization first: we want to check if there exists a vertex cover of size <= t (t up to 32). We can apply kernelization to reduce the graph to O(t^2) vertices and O(t^3) edges, then run recursion. Since we might need to try increasing t from 0 to maybe 32 (or binary search), we can do it efficiently.
But note: we need the exact minimum size. So we can find the minimum t <= K such that a vertex cover of size t exists. That is we can binary search between 0 and K, or just increment t from 0 upwards until we find a cover. Since K is only 32, we can just try t = 0,1,...,K. For each t, run a decision algorithm: is there a vertex cover of size <= t? If yes, output t and stop. If none, output "Impossible". This would involve up to 33 calls of the decision algorithm.
Each decision algorithm: given t <= 32, we need to decide existence of vertex cover of size <= t. We can kernelize based on t. But note: kernelization depends on the target size t. If we run for increasing t, we can reuse something? Possibly, but we can just kernelize for each t.
Alternatively, we can use a single recursive search that finds the minimum cover size directly, using a branch and bound algorithm that maintains a global upper bound (initially K+1) and a lower bound (e.g., size of a maximal matching). That might be more efficient because we only explore the search tree until we find a cover of size <= K; we also need to confirm if the minimum > K, we can stop early when lower bound exceeds K or search exhausts.
Given that K is small (<=32), I'd go with a standard FPT decision algorithm for each t. However, we need to be careful with performance: N up to 3000, M up to 30000; applying kernelization for each t might be fine as t <= 32, but we need to be careful about time. Let's analyze.
For each t, we run kernelization:
- Remove isolated vertices (degree 0).
- While there exists a vertex with degree > t, include it in the cover (decrement t, remove that vertex and all incident edges).
- After that, if t < 0 -> no.
- Also, if number of vertices > t * (max degree?) Actually, we can also apply the bound: if number of edges > t * (remaining vertices) ??? Not sure. But we could also apply a simple bound: if the remaining graph has more than t^2 vertices, then it's impossible (since each vertex not in the cover can have at most t edges, and cover has size <= t, so the independent set size <= t * t? Actually, if we have a vertex cover of size <= t, then the complement is an independent set. Each vertex in the independent set can be adjacent only to vertices in the cover. Since after reduction, maximum degree <= t (since we removed vertices with degree > t), each vertex in the independent set has degree at most t, and those edges go to cover vertices. But the cover has at most t vertices, so the total number of edges from cover to independent set is at most t * t (since each cover vertex can be adjacent to many independent vertices). However, the independent set vertices could be many? Wait, each edge incident to an independent set vertex must go to a cover vertex. So the total number of edges between cover and independent set is at most (size of cover)*(size of independent set?) Actually, each cover vertex can be adjacent to any number of independent vertices; the bound is not immediate. But there's a known kernel: After reduction, if |V| > t + t^2, then there is no vertex cover of size t. Because each vertex not in the cover is adjacent only to cover vertices, and since max degree <= t, the number of such vertices is at most t * (size of cover) <= t^2. So total vertices = cover + independent set <= t + t^2. So if |V| > t^2 + t, we can return false. That's a good rule to prune early.
Also, if number of edges > t * |V|? Possibly but not needed.
So after reduction, we have a graph with max degree <= t and |V| <= t^2 + t. For t <= 32, t^2+t <= 1056. That's small. Then we can run a recursive branching algorithm on this kernel.
Recursion: We maintain current graph (maybe as adjacency lists) and remaining budget r. We apply reduction rules at each node:
- If no edges: return true.
- If r == 0: return false (since edges remain).
- If there is a vertex with degree > r: must pick it (since we already removed degree > r? Actually after initial reduction, we have max degree <= t, but during recursion r may be smaller, so we might again encounter vertices with degree > r. So we should apply that rule at each node.)
- If there is a vertex of degree 1: we can pick its neighbor (since that is optimal). Actually, we can implement the rule: if degree 1 vertex exists, then include its neighbor (forced). Because any minimum cover of size <= r will include neighbor rather than leaf. So we can safely include neighbor, decrement r, remove neighbor and its incident edges.
- Also, if there is a vertex of degree 0, remove.
- Optionally, we could also apply crown reduction or other rules, but not necessary given small kernel and r <= 32.
Then if none of these apply, we pick an edge (u,v) and branch: either include u or include v. For each branch, we decrement r by 1, remove that vertex and all incident edges.
To make recursion efficient, we need to represent the graph and allow modifications that can be undone for backtracking, or we can copy the graph? Since kernel size is small (<= 1056), copying the graph each recursion may be okay if depth <= 32, but number of nodes in recursion tree can be up to 2^32 which is too many. But with the reduction rules, the search tree size is often much smaller, and FPT algorithms typically have worst-case O(2^r). But we need to ensure that we prune effectively and avoid exponential blow-up for r up to 32. O(2^32) is about 4 billion, which is too high. However, practical FPT algorithms for vertex cover with r=32 often run within time if good branching rules are used, especially with degree-2 folding, etc. But 2^32 is borderline. We can incorporate more powerful reduction rules like degree-2 folding (when a vertex has degree 2, we can do a transformation that reduces the graph size). That's typical in efficient implementations for vertex cover up to about 50. Also we can use memoization on graph signatures? Not necessary.
Alternatively, we can use the fact that K is at most 32, so we can apply a standard bounded search tree algorithm: pick an edge (u,v), branch include u or include v, and apply reduction rule: after including a vertex, we remove it and its incident edges. Also before branching, we can preprocess: if any vertex has degree 0, remove; if any vertex has degree > r, forced include; if degree 1, forced include neighbor. This reduces the branching factor. The worst-case complexity of such algorithm is O(1.466^r) or better if we consider more sophisticated branching on high-degree vertices. But we need to implement something relatively simple yet fast enough for r up to 32.
Given the constraints (N up to 3000, M up to 30000) and time limit unknown (probably 2-3 secs), we need a robust solution.
Another approach: Since K is at most 32, we can use a different technique: use integer programming? Not.
Or we can use the fact that the minimum vertex cover size is equal to |V| - maximum independent set. But maximum independent set is also NP-hard. However, we can use branch and bound with bitsets? Possibly using meet-in-the-middle: Since K is small, we can try to enumerate subsets of vertices of size up to K? There are C(3000, 16) huge, not possible.
So we rely on FPT.
Given that we only need to decide existence for t up to 32, we can also use a kernelization that reduces the graph to a kernel of size O(t^2) and then solve the kernel by transforming to a maximum matching? Wait, vertex cover in bipartite graphs is polynomial via Konig's theorem, but our graph is general. However, after kernelization we still have a general graph. But we can use a branch and bound.
Maybe we can use the fact that after kernelization, the number of vertices is at most ~1000, and we can use a standard exact algorithm for vertex cover, e.g., using recursive branching with a lower bound from maximum matching (since the size of a maximum matching gives a lower bound for vertex cover). That can prune many branches. We can compute a maximum matching quickly on the kernel (since kernel has up to 1000 vertices and edges maybe up to O(t^3)=~32k). We can compute maximum matching using Blossom algorithm? That's heavy. But we can use the fact that the lower bound from a maximal matching (greedy) is also a valid lower bound (though not as strong). For branch and bound, we can compute a greedy maximal matching to get a lower bound quickly. Or we can compute a maximum matching using a simple DFS augmenting path algorithm? But for general graphs, we need Blossom which is complex. However, we can use the fact that the graph is small (<=1000 vertices) and we only need a lower bound: we can compute a maximum matching using a simpler algorithm? Actually, we can use the fact that the lower bound from a maximal matching is enough: any vertex cover must be at least the size of a maximal matching (since edges in a matching share no vertices, each edge needs a distinct vertex in cover). But that lower bound may be far from optimum, but for pruning it might be acceptable. Since depth is small, we can just rely on branching.
Alternatively, we can use a known FPT algorithm that runs in O(1.2738^k + kn) due to Chen, Kanj, Xia (2010) using kernelization and bounded search with advanced branching. But implementing that from scratch might be heavy.
Given contest environment, it's plausible that a simpler recursive algorithm with reduction rules (degree > r, degree 0, degree 1, and maybe degree 2 folding) will pass with r up to 32 if implemented carefully (with adjacency list and backtracking by removing/restoring vertices). We need to ensure that the search tree size is not too large. Let's estimate worst-case. The worst-case for basic branching on an edge, without reductions, is 2^r. For r=32, that's 4 billion, too much. However, with reduction rules, the branching factor improves. In particular, if we always pick a vertex of maximum degree? Actually, typical FPT algorithms for vertex cover use the following: if there is a vertex of degree at least 3, then branching on it gives recurrence T(r) = T(r-1) + T(r-3) (if we include it, r-1; if we exclude it, we must include all neighbors -> at least 3 vertices). That yields a better bound. But we need to ensure that we handle degree 2 vertices specially: there's a folding rule that reduces the graph without branching. So overall, the worst-case complexity is about O(1.618^r) or even O(1.466^r). For r=32, 1.466^32 ≈ 1.466^10≈ 44, 1.466^20≈ 44^2=1936, 1.466^32≈ 441.466^22? Let's compute roughly: log2(1.466) ≈ 0.55, so 1.466^32 ≈ 2^(0.5532)=2^17.6≈ 2e5. Actually, 2^17.6 ≈ 200,000. So about 200k nodes. That's fine. But actual constant may be higher.
But we must also consider that after kernelization, the graph is small, so each recursive call's operations are cheap.
Thus a simple recursive algorithm with reduction rules (including degree > r, degree 1, degree 2 folding) should be sufficient.
Let's outline the plan:
Overall algorithm: For t from 0 to K:
- Run decision algorithm: Is there a vertex cover of size <= t?
- If yes, output t and exit.
If none, output "Impossible".
Decision algorithm for given t:
- Create adjacency list for the graph (global). But note that we will need to modify the graph during recursion; we can work on a copy of the graph after kernelization for each t? However, if we run for increasing t, we can reuse something but not needed.
Better: Write a function bool has_vc_size(int t) that takes the original graph and returns if there exists vertex cover of size <= t. It will first apply kernelization rules that may forcibly include some vertices (and reduce t). This kernelization will modify the graph (by removing vertices) and produce a reduced graph with some forced vertices. Since we don't need to preserve the original graph across t attempts, we can copy the graph each time. N up to 3000, M up to 30000, copying adjacency lists for each t (max 33 times) is acceptable.
So for each t:
- Make a copy of the adjacency lists (e.g., vector<vector<int>> adj(N+1)).
- Also maintain an array "deleted" or "alive" to mark vertices removed. Alternatively, we can actually remove vertices by deleting from adjacency and updating neighbors' lists. Since we need to backtrack in recursion, it's easier to maintain a state with sets of alive vertices and adjacency lists with deletions that can be undone. For kernelization, we don't need backtracking because it's a one-way reduction: we either include vertices (forced) and remove them, and we don't need to reconsider other choices. So kernelization is deterministic and we can apply it and produce a reduced graph and a count of forced vertices. After that, we need to run recursion on the reduced graph with remaining budget r = t - forced_count.
For recursion on the reduced graph, we need a backtracking algorithm. Since the reduced graph has at most t^2 + t vertices, we can implement recursion using a mutable graph representation with ability to revert changes. One common approach is to use "dynamically updating adjacency lists" with a stack of changes to undo. But given the size is small, we could also copy the graph at each recursive call. However, depth up to 32, copying the graph (size up to 1000 vertices and edges up to maybe 30k? Actually after reduction edges could be up to O(t^3)=~32768, copying that at each node could be costly but maybe okay if number of nodes is moderate (200k). 200k * copying 30k edges would be huge. So better to use an in-place modification with undo.
We can represent the graph as adjacency lists, and maintain a boolean array "active" indicating if a vertex is still in the graph. Also maintain for each vertex its current degree (number of active neighbors). When we remove a vertex (include it in cover or forced exclude), we need to decrement degrees of its neighbors and possibly mark it inactive. We'll also maintain a stack of changes to be able to undo the removal when backtracking. This can be done by storing the list of vertices that were removed, and for each neighbor, the fact that its degree decreased. But careful: To undo, we need to restore the state exactly. A simpler approach: Use a recursive function that receives a copy of the current set of active vertices and their adjacency lists? But copying the active set (bitset) might be easier: Since the kernel has at most about 1000 vertices, we can represent the graph as a bitset of adjacency? That could be efficient: For each vertex, have a bitset of neighbors (size up to ~1000). Then removal is clearing rows and columns? Actually, we can maintain a bitset for each vertex, but we would need to update many bitsets when removing a vertex; or we can just ignore removal and keep the full adjacency but use an "active" mask. For branching, we need to pick an edge among active vertices. We can use a global array of adjacency bitsets (or adjacency lists) and maintain an integer mask of active vertices (using a bitset of up to 1056 bits). Since 1056 bits is about 17 64-bit words, that's manageable. Then operations like find a vertex with degree > r among active vertices can be done by iterating over set bits and checking degree computed on the fly using bitset AND with active mask. This avoids having to update adjacency lists when removing vertices; we only need to update active mask. The degree of a vertex is the number of neighbors that are active. So we can compute it as popcount(adj[v] & activeMask). That's efficient if we use bitset operations. For N up to 3000, we could even use bitset of size N (3000 bits) which is about 47 64-bit words, still okay. But note: The kernel after reduction is not necessarily the entire original graph; after forced inclusions, we might have removed many vertices, but the remaining graph could still be up to 3000 vertices? Actually, after kernelization we might have a graph with max degree <= t, but if t is up to 32, we still might have many vertices. But the bound |V| <= t^2 + t only holds if there exists a cover of size <= t; but if there is no cover, we might detect that via the bound and return false early. However, during recursion we need to handle cases where the graph may be larger but we are still exploring. To ensure efficiency, we want to apply kernelization before recursion to shrink the graph to O(t^2) in all cases, else we can early return false. So we can force that: in the decision function, after applying forced includes for high-degree vertices, if t becomes negative, return false; then after that, if the number of active vertices > t*(t+1) (i.e., > t^2 + t) then return false (since no cover of size t exists). This is a safe bound: if there is a vertex cover of size t, then the independent set size is at most t^2? Let's verify: In any graph with maximum degree <= t, if there is a vertex cover of size <= t, then the complement is an independent set, and each vertex in the independent set has degree <= t and all its neighbors are in the cover. The cover has at most t vertices, so each vertex in the independent set can be adjacent to at most t cover vertices, but there could be many independent vertices adjacent to the same cover vertex. However, the total number of edges between cover and independent set is at most t * (size of cover) = t * t? Wait, no: each cover vertex can have degree up to t (since max degree <= t). So each cover vertex can be adjacent to at most t vertices (including possibly other cover vertices). But the independent set vertices only connect to cover vertices. So the total number of edges from independent set to cover is at most t * (size of cover) because each cover vertex has at most t edges total, but some of those edges might be to other cover vertices. So the number of edges incident to cover vertices that go to independent set is at most t * (size of cover) minus edges among cover. This is at most t * (size of cover). Each independent vertex must have at least one edge to the cover (otherwise it would be isolated and we would have removed it). But it could have multiple edges. However, we can bound the number of independent vertices: each independent vertex has at least 1 edge to the cover. But each cover vertex can have at most t edges to independent vertices. So the number of independent vertices is at most t * (size of cover) because each independent vertex contributes at least one edge, and each cover vertex can account for at most t edges. So indeed |I| <= t * |C|. Since |C| <= t, we get |I| <= t^2. So total vertices = |C|+|I| <= t + t^2. This holds regardless of the existence of a cover? This is a necessary condition for existence of a cover of size t. So if after reducing high-degree vertices (so max degree <= t) and we still have more than t^2 + t vertices, then no cover of size t exists. So we can prune.
Thus, after kernelization (including forced includes for degree > t and removal of isolated vertices) we have a graph with max degree <= t. If its vertex count > t^2 + t, return false. Otherwise, we have a small kernel (<= 1056). Good.
Now we can run recursion on this kernel. Since the kernel is small, we can use a simple representation: we can map the remaining vertices to indices 0..m-1 (where m <= 1056). Then we can store adjacency as bitsets using C++ std::bitset where maxN maybe 1056? But we can also use vector adjacency lists; since m is small, operations like iterating over neighbors are okay. However, we need to handle dynamic removal and restoration for backtracking. Using bitset and active mask is convenient: we can maintain a global bitset for each vertex (adjacency) and a global active mask (bitset). For branching, we need to pick an edge (u,v) with both active. We can iterate to find a vertex u with minimum degree? Possibly pick vertex with highest degree to get good branching.
But we also need to apply reduction rules during recursion: (1) if active mask has no edges (i.e., all degrees zero) -> success; (2) if remaining budget r == 0 -> failure; (3) If any vertex has degree > r: must include it (forced include). (4) If any vertex has degree 1: we can include its neighbor (forced). (5) Possibly degree 2 folding.
We need to be careful with forced inclusion for degree > r: Since we might have removed high-degree vertices earlier, but r may be smaller now, so vertices with degree > r may appear.
Also, for degree 1: we need to find a leaf. The rule: if there is a vertex v with degree 1, then there exists an optimal cover that includes its neighbor u (the only neighbor) rather than v. So we can safely include u. However, we must be careful: In the context of decision (whether a cover of size <= r exists), we can apply this reduction: if there is a leaf v, then any vertex cover of size <= r must include u, because if we include v, we could replace v with u and not increase size. But is it always true that if there exists a cover of size <= r, then there exists one that includes u? Yes, because given any cover that includes v, we can replace v with u to get a cover of same size or smaller (since u might already be in cover). So we can safely force include u, reduce r by 1 (if u not already in cover? Actually, we include u. If u is already in the cover, then we don't need to decrement r? But we are adding u to the cover; if it's already selected, then we don't need to add. However, in the reduction we don't know if u is already selected; we are deciding to include it. So we can just add u to cover (if not already included), and remove u and its incident edges. However, to be safe, we should treat the reduction as: we can include u (i.e., choose u) and remove both u and v. This is valid because any optimal cover can be transformed to include u. So in the decision algorithm we can force include u, decrement r by 1, and remove u and all its incident edges (including the edge to v). This may also remove other leaves etc.
Implementation detail: When we include u, we remove u and all its neighbors become degree reduced. So we can apply this reduction repeatedly.
Now, degree 2 folding: For a vertex v of degree 2 with neighbors a and b. There is a known reduction: if a and b are adjacent (i.e., there is an edge between a and b), then v is part of a triangle? Actually, if a and b are adjacent, then any vertex cover must include at least two vertices from {v, a, b} to cover edges (v-a, v-b, a-b). In that case, there is always an optimal cover that includes a and b (since including v alone covers v-a and v-b but not a-b). The standard reduction: if a and b are adjacent, then we can include a and b in the cover (i.e., force include both) and remove v, a, b? Actually, we can instead apply a rule: if degree 2 vertex v has neighbors a and b that are adjacent, then we can safely include both a and b? That would increase cover size by 2, but we might do better? Let's recall the standard folding rule for vertex cover: For a vertex v of degree 2 with neighbors u and w (non-adjacent), we can contract u and w into a new vertex and reduce the problem, effectively reducing the budget by 1. For degree 2 with neighbors adjacent, we can apply a different rule: we can include v? Actually, there is known reduction: If v has degree 2 and its neighbors u and w are not adjacent, then we can "fold" v: remove v, u, w and add a new vertex representing the union, and the budget reduces by 1. If u and w are adjacent, then v is part of a triangle, and we can safely include u and w? Actually, consider triangle (u,v,w). Minimum vertex cover of a triangle is size 2 (any two vertices). So we can decide to include u and w, but that might not be optimal if there is a global context. However, standard FPT algorithms often include folding for degree 2 to avoid branching. For simplicity, we may skip degree 2 folding and just branch on an edge. But then worst-case branching factor might be higher if the graph has many degree 2 vertices. However, degree 2 vertices might lead to chains and we can use other reductions like if degree 2 vertex, we can branch on its neighbors? But perhaps the simple algorithm with degree > r and degree 1 rules and picking a vertex of maximum degree may already be fast enough for r up to 32, given the kernel size is at most 1056. The worst-case for simple branching (without folding) occurs when all vertices have degree 2? Actually, a graph where all vertices have degree 2 is a collection of cycles. For a cycle, the minimum vertex cover size is ceil(n/2). For a cycle of length L, to decide if a cover of size r exists, you can solve exactly. Branching on an edge on a cycle: pick an edge (u,v). If you include u, you remove u and its incident edges, the graph becomes a path; if you include v, similar. This leads to a recurrence T(r) = 2T(r-1) perhaps, because after including u, the remaining graph still has many edges. Actually, on a cycle, branching on a vertex of degree 2 leads to recurrence T(r) = T(r-1) + T(r-2) maybe? Let's think: If we include u, we remove u and its two neighbors? Actually, including u removes u and edges incident; the cycle becomes a path of length L-2 (with endpoints maybe still connected? Let's model: Cycle vertices v1-v2-...-vL. Include v1: remove v1 and edges (v1-v2) and (v1-vL). The remaining graph is a path from v2 to vL (with edge v2-v3...-vL). The path's vertex cover size is something. The recurrence may be like T(r) = T(r-1) + T(r-2) because if you include v1, you need to cover the path with r-1; if you exclude v1, then to cover edges (v1-v2) and (v1-vL), you must include v2 and vL, so you include both, reducing budget by 2, and also remove them and their incident edges, leaving a path of length L-3? This yields T(r) = T(r-1) + T(r-2). That gives Fibonacci growth ≈ 1.618^r. So even without folding, cycles yield a decent branching factor. For degree >=3, branching factor is better. So the basic algorithm might be acceptable.
But to be safe, we can implement degree 2 folding for non-adjacent neighbors (the standard folding) to reduce branching further. It's not too complicated: When we encounter a vertex v of degree 2 with neighbors u and w that are not adjacent, we can apply folding: Remove v, u, w and introduce a new vertex x that is adjacent to all neighbors of u and w (except v and each other). The problem reduces to finding a vertex cover of size r-1 in the new graph. In terms of decision, if we have a vertex cover of size r in the original graph, then either u or w is in the cover? Actually, the folding rule: In any minimum vertex cover, either v is in the cover, or both u and w are in the cover. But we can contract: replace {u, w} with a new vertex and reduce budget by 1. More precisely, the rule: There is always a minimum vertex cover that either includes v, or includes both u and w. The folding operation creates a new graph where we remove v,u,w and add a new vertex x, connect x to all vertices that were adjacent to u or w (except v). Then the original graph has a vertex cover of size <= r iff the new graph has a vertex cover of size <= r-1. That's a safe reduction.
Implementing folding with our mutable graph representation could be a bit more involved, but still doable. It might be worth it to speed up.
Alternatively, we could use a simple branching algorithm without folding, but with a good heuristic for picking the next vertex/edge. For r up to 32, and kernel size up to ~1000, I think a well-coded recursion with the simple rules (including forced includes for degree > r, degree 1, and maybe also a lower bound to prune) should pass within time limits typical for programming contests. Let's test worst-case: a cycle of length 2000, but we have kernel bound: after reduction (max degree <= t) but t maybe 16? Actually, if we are checking t=16, then max degree <= 16, but cycle has degree 2, so it's fine. Number of vertices in kernel can be up to t^2 + t = 272 for t=16? Wait, if t is small, kernel bound ensures that if the graph after forced includes (which doesn't happen for cycle because degree 2 <= t) still has many vertices (say cycle of length 3000) and t is 16, then because |V| > t^2 + t (which is 272), we can immediately return false. That's because if there is a vertex cover of size <= t, then the graph must have at most t^2 + t vertices, given max degree <= t. So for a long cycle, if t is less than about sqrt(N), then we quickly say impossible. So the recursion only runs on graphs with at most about 1000 vertices. For t near 32, kernel size is at most 1056. So recursion deals with graphs up to 1056 vertices.
Now, consider a graph that is a large collection of disjoint edges? That's a matching. In a matching, degree 1 for each vertex. Degree-1 reduction would force include one endpoint each time? Actually, for an edge (u,v) with both degree 1 (isolated edge), the degree-1 rule: if u is degree 1, we include its neighbor v. But then v might have degree 1 as well, so including v covers both u and v. So we would cover each edge with one vertex, reducing budget by 1 per edge. This is linear and no branching.
Consider a graph that is a perfect matching plus some extra connections that cause branching. But likely recursion depth will be limited.
Thus, a simple recursion with rules (forced include for degree > r, degree 1, and if none, pick a vertex of maximum degree and branch: include it or exclude it (which forces include all its neighbors)) should be okay.
But we need to be careful: The standard algorithm for vertex cover FPT is:
VC(G, r):
if no edges: return true
if r == 0: return false
if there exists a vertex v with degree > r: return VC(G - {v}, r-1) // forced include
if there exists a vertex v with degree == 1: (let u be its neighbor)
// we can include u
return VC(G - {u}, r-1) // because we can always include u in an optimal cover
else:
pick a vertex v of maximum degree
return VC(G - {v}, r-1) or VC(G - N(v), r - deg(v)) // include v, or exclude v meaning include all neighbors
But the exclude case: if we exclude v, then to cover edges incident to v, we must include all its neighbors. So we remove v and its neighbors, and reduce r by deg(v). This branching is effective because deg(v) >= 2 (since degree 0 and 1 are handled, and degree > r handled). If deg(v) >= 3, recurrence is T(r) = T(r-1) + T(r-d) where d >= 3, which is bounded by about 1.465^r. If deg(v)=2, then T(r) = T(r-1) + T(r-2), which is Fibonacci ~ 1.618^r. That's fine.
However, we must also handle the case where v has neighbors that might be overlapping (if graph has multiple edges? No). It's fine.
But there is nuance: In the exclude case, we include all neighbors. However, after we include those neighbors, they may have edges among themselves, but they are removed along with their incident edges. So we effectively remove N[v] (closed neighborhood) from the graph.
Implementation wise, we need to be able to remove a set of vertices (single or multiple) and later restore them when backtracking. So we need a data structure that supports removal and restoration with stack.
Simpler: Since kernel size is small, we could use a recursive algorithm that at each step copies the entire graph (like using bitset and active mask). Copying the bitset for each node might be okay if the number of nodes is not huge. For each recursive call, we can make a copy of the active mask (and maybe a copy of the state of forced includes?). The active mask is a bitset of size up to ~1056, which is about 17 words. Copying that is cheap. However, we also need adjacency information. If we use a static adjacency matrix (bitsets) for all vertices in the kernel, and we maintain an active mask, then copying the active mask for each recursive call is just copying a few words. That's fine. The graph itself doesn't change; only the set of active vertices changes. So we can represent the graph as a vector<bitset> adj for each vertex (indexed 0..n_kernel-1). We'll also need to compute degrees on the fly: deg(v) = (adj[v] & active).count(). We'll need to quickly find a vertex with max degree, or check for degree > r, degree 1, etc. This can be done by iterating over set bits in active mask and computing degree each time (or caching degrees and updating them when vertices are removed). But since the active set size is at most 1056, and we might do many recursive calls, recomputing degrees from scratch each time by scanning all active vertices and counting bits might be acceptable if recursion depth is limited and the number of nodes in the search tree is maybe up to few hundred thousand. Each degree computation involves a bitwise AND and popcount. For 1056 bits, that's about 16-17 64-bit words, popcount using builtin functions (__builtin_popcountll on each word) which is fast.
Thus, we can implement recursion as:
bool solve(const bitset& active, int r) {
// check if there are any edges: if sum of degrees > 0
// We can check by iterating over active vertices and if any degree>0.
// also if r < 0 return false? Actually r is remaining budget.
if (no_edges(active)) return true;
if (r == 0) return false;
// reduction: forced include for degree > r
for each v in active:
if (deg(v) > r) {
// include v
bitset<MAXK> new_active = active;
new_active.reset(v); // remove v
return solve(new_active, r-1);
}
// reduction: degree 1
for each v in active:
if (deg(v) == 1) {
// find its neighbor u (the only neighbor in active)
// include u
bitset<MAXK> new_active = active;
new_active.reset(u); // remove u
return solve(new_active, r-1);
}
// else pick a vertex v with max degree (>=2)
// if deg(v) == 0, then no edges (should have been caught)
// Branch:
// Option 1: include v
bitset<MAXK> active1 = active;
active1.reset(v);
if (solve(active1, r-1)) return true;
// Option 2: exclude v => include all neighbors
bitset<MAXK> active2 = active;
active2.reset(v);
for each u where adj[v] test is 1 and active2[u] is 1:
active2.reset(u);
int neighbors_included = count of such u;
if (neighbors_included <= r) { // but we already have deg(v) <= r because we handled degree > r
if (solve(active2, r - neighbors_included)) return true;
}
return false;
}
But we also need to account for the possibility that after including neighbors, the graph might have new forced rules, etc.
This approach is simple and should work.
We also need to handle the case where after removal of vertices, there might be isolated vertices; they don't affect the existence of edges. The "no_edges" condition can be: if for all active v, deg(v)==0, then true. But that's equivalent to checking if the total number of edges (sum deg/2) is zero. We can compute quickly by iterating over active vertices and break when we find a vertex with deg>0.
But we also need to handle the degree-1 rule: we must include the neighbor. However, what if the neighbor is also degree 1? Then including it is fine. However, we need to be careful: if we have two leaves attached to the same vertex, including that vertex covers both leaves, good.
But is it always safe to force include the neighbor? In the decision problem for a given r, if there is a vertex cover of size <= r, then there exists one that includes the neighbor. So we can apply this reduction deterministically. Yes.
However, in our recursion, after applying forced include for degree > r, we might have a leaf. But note: the leaf's neighbor might have degree > r? Possibly, but if degree > r, we would have already forced include it earlier. So after that, neighbor's degree <= r. So including it is okay.
Now, we also need to consider that the graph might have multiple connected components. Our recursion as described will handle them because we just check globally for edges.
But we must also consider that after applying the degree-1 reduction, we are making a recursive call with r-1. This reduction is safe, but it may not be optimal in terms of search tree size? It's fine.
Potential issue: In the exclude branch, we include all neighbors. But what about the case where some neighbor is also v? No.
Now, about kernelization before recursion: We'll apply deterministic reduction rules that do not branch. We'll also remove isolated vertices. We'll also include vertices of degree > t (the current budget). For each such vertex, we include it, decrement t, and remove it and its incident edges. We also after that remove any resulting isolated vertices. We repeat until no vertex with degree > t exists. Then we check if number of vertices > t^2 + t, then return false. Also if t < 0, false. Then we run recursion on the remaining graph with budget t.
But note: The recursion algorithm itself also applies the same reduction rules (degree > r, degree 1) at each node. However, after kernelization, we are guaranteed that max degree <= t and no degree 0 vertices (maybe isolated are removed). But during recursion, r may become smaller, so degree > r may appear. Also degree 1 may appear after removals. So we still need to apply those rules in recursion.
Now, the recursion we described uses a bitset representation based on the kernel graph. The kernel graph may have up to ~1000 vertices. We'll map the remaining vertices to indices 0..nk-1. We'll build adjacency bitsets for them. For kernelization, we need to compute the reduced graph after forced inclusions. This reduction can be done using similar operations on the original graph but with a simpler approach because it's one-way.
We have original graph with N up to 3000. For a given t, we need to compute forced includes. We'll maintain an array "deleted" or "active". Since we need to repeatedly remove vertices with degree > t and also remove isolated vertices. But note: as we include vertices, t decreases, so the condition degree > t changes (since t changes). So we need to iteratively check for vertices with degree > current remaining budget. So kernelization can be performed as:
Input: graph (adj lists), budget t.
Set forced = 0.
Maintain an array "alive" (bool) initially all true.
Maintain degree array for each vertex (current degree considering alive neighbors).
Initialize degree for each vertex.
Loop:
- Remove all vertices with degree 0 (isolated) by marking alive false.
- Find a vertex v with alive true and degree > (t - forced). (Because remaining budget is t - forced.)
If found: include v (forced++), mark v as dead, update degrees of its neighbors (decrement). Continue loop.
- If none, break.
After loop, if forced > t: return false (impossible).
Otherwise, let remaining_vertices = list of alive vertices. Let count = number of alive vertices.
If count > (t - forced)^2 + (t - forced): return false.
Otherwise, build kernel graph from remaining vertices: create mapping from original index to new index 0..nk-1. Build adjacency matrix (bitset) for these vertices.
Now call recursive function solve_kernel(active_mask initial all bits set (all nk vertices active), budget r = t - forced).
The recursion will also apply reductions.
But note: In the kernel, we might still have isolated vertices because after forced includes we removed all isolates? Actually, we removed isolates in the loop, so the kernel should have no isolated vertices. However, during recursion, after we remove vertices, isolates may appear, but they will be handled by the "no edges" check.
Now, we need to ensure that the recursion algorithm is correct and efficient.
Potential improvements: In recursion, before branching we can also compute a lower bound to prune: e.g., compute a maximal matching quickly to get a lower bound on the minimum vertex cover size. Since for any vertex cover, size >= size of any matching. So if the size of a maximal matching in the current graph > r, then we can return false. This can prune many branches. Computing a maximal matching in a graph represented by an active mask with up to 1000 vertices can be done by a greedy algorithm: iterate over vertices, if a vertex is unmatched, try to match it with an unmatched neighbor. This is O(|V| + |E|) which is acceptable. However, we need to do this at each recursive node; that could be costly if done many times. But we can compute a quick lower bound using the fact that the graph has max degree <= t (which is <= 32) and the number of vertices is small, maybe we can compute a matching via simple DFS? Or we can compute a lower bound as ceil( number_of_edges / (max_degree) )? Not reliable. But the matching lower bound is powerful. However, we might not need it because the branching already reduces quickly. But to be safe, we can implement it.
Given the small kernel, we can compute a maximal matching each time by scanning all active vertices and for each, if it's not matched, look for an unmatched neighbor (using adjacency bitset & active mask). This is O(nk * degree) ~ O(nk * t) per call, which is okay if the number of recursive calls is not huge. But if we have up to 200k nodes, each matching computation might be heavy: 200k * 1000 * 32 = 6.4e9 operations, too many. So we need to be careful. Instead, we can compute a simpler lower bound: Since the graph has no vertices of degree > r (we already handled), we could use the fact that if sum of degrees > r *