I can confirm that the answer for this test case should indeed be 3. {1, 2, 4} and {1, 4, 5} are vertex covers of the graph; all edges are covered. It is also minimum because there are no solutions with 2 vertexes (checked by hand and by code).
See this code snippet for the minimum vertex cover:
#include <bits/stdc++.h>
using namespace std;
struct edge {
int x, y; // two endpoint of edges
};
int n, m, s = -1; // n = number of nodes, m = number of edges, s = answer
vector<edge> g; // graph
vector<bool> nodeColored; // whether node is colored
void dfs(int x, int c);
int main() {
cin >> n >> m; // read number of nodes, number of edges
nodeColored = vector<bool>(n+1); // initialize
for(int i = 1; i <= m; ++i) {
edge newEdge;
cin >> newEdge.x >> newEdge.y;
g.push_back(newEdge);
}
dfs(1, 0); // consider first node, no nodes have been colored yet
cout << s << endl;
return 0;
}
void dfs(int x, int c) { // x = considering node x, c = c nodes already colored
if(x > n) {
// all nodes have been considered, simply run check
bool ok = true; // assume this coloring is ok
for(edge i : g) {
if(!nodeColored[i.x] && !nodeColored[i.y]) { // not a vertex cover?
ok = false;
}
}
if(ok) { // we should update answer
if(s == -1) s = c; // s = -1 entails answer has never been set
else s = min(s, c); // min vertex cover
}
return;
}
dfs(x+1, c); // ignore this node
nodeColored[x] = true;
dfs(x+1, c+1); // color this node
nodeColored[x] = false;
return;
}
I have tried to make the code as intuitive as possible, as well as add comments in order to make the meaning behind each line of code clearer.
Texting against this input, which is the one you provided (note that for the first line, 4, 8
means there are 4 nodes and 8 edges):
4 8
1 4
1 5
1 2
4 1
2 4
3 4
5 2
1 3
The output is:
3
This should be a correct output.