To solve this problem, we need to determine the minimum number of vertex flips required to make all edges in an undirected graph the same color (either all red or all blue). Each vertex flip changes the color of all edges incident to it. The solution involves solving a system of equations over GF(2) for each target color and finding the optimal solution.
Approach
-
Problem Analysis:
- Each edge's color can be toggled based on the number of flips of its incident vertices. The goal is to find the minimum flips required to make all edges either red or blue.
-
Formulating Equations:
- For each edge, we determine if the desired target color (either red or blue) requires an even or odd number of flips on its endpoints. This forms a set of equations over GF(2).
-
Graph Representation and Constraints:
- Construct an adjacency list for each target color, encoding the required parity for each edge.
-
Feasibility and Solution:
- For each target color, use BFS to check if the system of equations is feasible and compute the minimum flips required. Track for each connected component whether flipping all node assignments (inverting the solution) yields a better result.
-
Result Selection:
- Compare the results for both target colors and select the minimum number of flips. If neither target is feasible, return -1.
Solution Code
#include <bits/stdc++.h>
using namespace std;
using ll = long long;
using vi = vector<int>;
using vvi = vector<vi>;
struct EdgeInfo {
int u;
int v;
char c;
};
struct Component {
vector<int> nodes;
bool invert;
};
vector<Component> processTarget(const vector<EdgeInfo>& edges, int n, char target_color) {
vector<vector<pair<int, int>>> adj(n + 1); // adj[node] contains (to_node, equation_c)
for (const auto& e : edges) {
int u = e.u, v = e.v;
bool same_color = (e.c == target_color);
int equation_c = same_color ? 0 : 1;
adj[u].emplace_back(v, equation_c);
adj[v].emplace_back(u, equation_c);
}
vector<bool> visited(n + 1, false);
vector<int> x0(n + 1, -1); // stores base assignment (starting with 0)
vector<Component> components;
bool feasible = true;
for (int u = 1; u <= n; ++u) {
if (!visited[u] && x0[u] == -1) {
if (!feasible) break;
queue<int> q;
q.push(u);
visited[u] = true;
x0[u] = 0;
vector<int> component_nodes;
component_nodes.push_back(u);
while (!q.empty()) {
int node = q.front();
q.pop();
for (const auto& edge : adj[node]) {
int v = edge.first;
int requirement = edge.second;
if (x0[v] == -1) {
int x_v = (requirement - x0[node]) % 2;
x0[v] = x_v;
visited[v] = true;
component_nodes.push_back(v);
q.push(v);
} else {
if ((x0[node] + x0[v]) % 2 != requirement) {
feasible = false;
while (!q.empty()) q.pop();
break;
}
}
if (!feasible) break;
}
if (!feasible) break;
}
if (!feasible) break;
// compute for this component's stats
int sum = 0;
for (int node : component_nodes) {
sum += x0[node];
}
int sz = component_nodes.size();
int count0 = sum;
int count1 = sz - count0;
components.push_back({component_nodes, count1 < count0});
}
}
if (!feasible) {
components.clear();
}
return components;
}
int main() {
ios::sync_with_stdio(false);
cin.tie(0);
int n, m;
cin >> n >> m;
vector<EdgeInfo> edges;
edges.reserve(m);
for (int i = 0; i < m; ++i) {
int u, v;
char c;
cin >> u >> v >> c;
edges.push_back({u, v, c});
}
auto comp_R = processTarget(edges, n, 'R');
auto comp_B = processTarget(edges, n, 'B');
int best = -1;
vector<_CHILD param_Warning: replace this with the actual type or variable name> flips;
bool use_R = false;
int steps_R = -1, steps_B = -1;
if (!comp_R.empty()) {
int sum = 0;
for (const auto& comp : comp_R) {
if (comp.invert) {
sum += (comp.nodes.size() - comp.nodes.size() / 2 * 2); // actually just comp.nodes.size() - count0
} else {
sum += comp.nodes.size(); // no, wait: count0 was assuming it's better not to invert. Wait:
// sum was count0 if not invert, count1 otherwise. But the components' invert is min between the two.
// So comp.invert is whether we choose the other option to get min. So:
// the count is (count1 if invert is on, count0 otherwise)
int count0 = 0;
for (int node : comp.nodes) {
count0 += (comp_R.empty()) ? 1 : (x0[node] of R case... but we don't track it).
// wait actually the function, in the code I wrote C++ outline, doesn't store the x0.
// Maybe the component structure should track sum0 and sz so that counts are known.
This is a problem in the code above.
Hmm, in my previous approach pseudocode, the component_data needs to store either count0 and sz so that they can compute between the two options.
I see that in my outline, for each component after processing in BFS phase, we compute count0 and decide whether invert or not.
But in the C++ code, the component structure must store information like count0 and sz in order to track it.
I think the correct C++ code would have to track those.
To simplify, perhaps each component stores count0 and sz.
So:
revised struct:
struct Component {
vector<int> nodes;
int count0;
bool invert; // whether it is better to invert (taking count1)
};
then in processing:
int sz = component_nodes.size();
count0 = sum;
count1 = sz - count0;
component.count0 = count0
invert = count1 < count0;
components.push_back( component );
thus, for the return components, we can have access to count0 and sz to compute steps.
Hence in code, need to adjust struct.
Thus adjusting the earlier code's Component:
struct Component {
vector<int> nodes;
int count0;
bool invert;
};
then when processing, after compute sum:
count0 = sum;
thus components are added as Component with nodes, count0, and invert.
Then in steps calculation: components cumulative min(count0, sz -count0) is the sum of each components contribution (min( count0, . . . )).
However, in the pseudocode outline:
in processTarget, each function returns vector of components, which includes info on count0 and sz.
Therefore, the steps for R is the sum over components of min(count0, component.sz -count0 ). But in code, while processing, the 'components' vector's components would have the count0 and the sz is their nodes' size. So steps_R is sum of (invert ? (sz -count0) : count0) for each component.
Thus in main:
if (comp_R has components):
steps_R is:
steps_r =0;
for (auto& comp : comp_R ){
steps_r += ( comp.invert ? ( (int)comp.nodes.size() - comp.count0 ) : comp.count0 );
}
similarly for B.
Then, once we have the steps R and B:
...
Thus, proceeding accordingly.
the condition is that components is not empty (feasible), then steps_r is computed as explained.
In the code for main:
So perhaps, in the code, I need to:
After 获取到 components for R, compute whether it is feasible ((components is not empty), since if unfeasible, it will have been empty.
steps_R can be computed as:
int steps_R = 0;
for (const auto& comp : comp_R) {
int sz = comp.nodes.size();
int opt = comp.invert ? (sz - comp.count0) : comp.count0;
steps_R += opt;
}
So replace the previous analysis.
Then proceed.
Then, similarly for B's steps_B:
But the code initially would have the components for B:
comp_B = processTarget(..., 'B');
then steps is computed.
Then, for those, if feasible:
steps_B = ...
Thus, code outline would have the following variables:
bool R_feasible = !comp_R.empty();
bool B_feasible = !comp_B.empty();
Then, in the main logic:
if neither is feasible:
output -1.
else, if one is feasible choose that.
else, choose the minimum between steps_R and steps_B.
once selected, it is then possible to Back to build the list of nodes to flip.
To build the flip list:
If selected target is R:
the components from comp_R are used.
For each component in those:
invert = comp.invert.
for each node in component's nodes:
base_x = ( ... ? current base_x is stored as x0[node]
but in the current approach, the base_x can be re-calculated (if we have nodes and the x0 was built during BFS).
but since we cannot track that in the stored components, perhaps during processing, components should keep the x0?
perhaps need to have a more comprehensive component struct:
but storing the base assignments would be expensive.
Alternatively, during the bfs processing, and during flipping, re-calculate the x0.
Yes, because during the BFS for each component, the base assignment comes from starting with 0 for the node, and setting descendants accordingly.
Thus to restore the base assignment:
For the final configuration, for each node:
For when the target is chosen (say R), and for a component's nodes:
the base_x is x0[u] from the BFS of R's processing.
but since the base_x isn't stored in the components struct, perhaps we need to reprocess.
However, this is computationally prohibitive for large n.
Thus alternative approach:
During the BFS processing in the function 'processTarget', we can track for each node its base assignment (x0).
But storing this would use O(n) space, which is feasible.
In C++:
So, for the components vector, we also have to track for each component its nodes and the base_x values.
or:
Wait, the function 'processTarget' could return both the feasibility and the components list along with the x0 array.
Thus, revise the processing function to return:
- feasible: flag.
- total steps if feasible.
- the components list (for building the solution)
- the array of base_x (size n+1), so it can be reconstructed.
由此,函数processTarget将返回这些信息。 Hence:
The function could return:
Tuple<bool, int, Component*, vector<int>>.
Such that the components store their nodes, and the vector<int, vec_x0> has the base x0 for each node.
Thus, rethinking the code structure:
Perhaps better to have the proceesTarget function returns a struct with the needed data:
struct Result {
vector< pair<int, bool> > components_inverse; // for each component, which is a set of nodes, and invert flag?
vector<int> x0_base; // base assignments (without inversion).
bool feasible;
int steps;
// perhaps the components need to track node lists to know which to flip.
// Alternatively, keep track for each node's component's invert flag.
vector<bool> invert_flags; // of size n+1: for each node, whether to invert it.
// but how to track.
Hmm. This is getting complex.
An alternative approach is: once we determine for each node whether to invert its base value,
we can simply mark for each node whether to include it in the flips.
Thus, during the processing phase, the components data needs:
For each component, its nodes and whether to invert (the component's flag).
Thus, to build the flip list:
For all nodes, their contribution is:
base_x (from x0_array) is the base assignment (starting with 0).
然后, if the component for this node had invert flag is ON, then the actual value is (base_x ^1).
thus, the final x value is (base_x ^ invert_component), and if it is 1, it is flipped.
Hence, during the return of processTarget, the function can also include the invert flags per component, along with the component decomposition.
Thus, I think it better to manage the processing function's return includes:
- feasible flag.
-