|
| 1 | +// Program to print Vertex Cover of a given undirected graph |
| 2 | +#include<iostream> |
| 3 | +#include <list> |
| 4 | +using namespace std; |
| 5 | + |
| 6 | +// This class represents a undirected graph using adjacency list |
| 7 | +class Graph |
| 8 | +{ |
| 9 | + int V; // No. of vertices |
| 10 | + list<int> *adj; // Pointer to an array containing adjacency lists |
| 11 | +public: |
| 12 | + Graph(int V); // Constructor |
| 13 | + void addEdge(int v, int w); // function to add an edge to graph |
| 14 | + void printVertexCover(); // prints vertex cover |
| 15 | +}; |
| 16 | + |
| 17 | +Graph::Graph(int V) |
| 18 | +{ |
| 19 | + this->V = V; |
| 20 | + adj = new list<int>[V]; |
| 21 | +} |
| 22 | + |
| 23 | +void Graph::addEdge(int v, int w) |
| 24 | +{ |
| 25 | + adj[v].push_back(w); // Add w to v’s list. |
| 26 | + adj[w].push_back(v); // Since the graph is undirected |
| 27 | +} |
| 28 | + |
| 29 | +// The function to print vertex cover |
| 30 | +void Graph::printVertexCover() |
| 31 | +{ |
| 32 | + // Initialize all vertices as not visited. |
| 33 | + bool visited[V]; |
| 34 | + for (int i=0; i<V; i++) |
| 35 | + visited[i] = false; |
| 36 | + |
| 37 | + list<int>::iterator i; |
| 38 | + |
| 39 | + // Consider all edges one by one |
| 40 | + for (int u=0; u<V; u++) |
| 41 | + { |
| 42 | + // An edge is only picked when both visited[u] and visited[v] |
| 43 | + // are false |
| 44 | + if (visited[u] == false) |
| 45 | + { |
| 46 | + // Go through all adjacents of u and pick the first not |
| 47 | + // yet visited vertex (We are basically picking an edge |
| 48 | + // (u, v) from remaining edges. |
| 49 | + for (i= adj[u].begin(); i != adj[u].end(); ++i) |
| 50 | + { |
| 51 | + int v = *i; |
| 52 | + if (visited[v] == false) |
| 53 | + { |
| 54 | + // Add the vertices (u, v) to the result set. |
| 55 | + // We make the vertex u and v visited so that |
| 56 | + // all edges from/to them would be ignored |
| 57 | + visited[v] = true; |
| 58 | + visited[u] = true; |
| 59 | + break; |
| 60 | + } |
| 61 | + } |
| 62 | + } |
| 63 | + } |
| 64 | + |
| 65 | + // Print the vertex cover |
| 66 | + for (int i=0; i<V; i++) |
| 67 | + if (visited[i]) |
| 68 | + cout << i << " "; |
| 69 | +} |
| 70 | + |
| 71 | +// Driver program to test methods of graph class |
| 72 | +int main() |
| 73 | +{ |
| 74 | + // Create a graph given in the above diagram |
| 75 | + Graph g(7); |
| 76 | + g.addEdge(0, 1); |
| 77 | + g.addEdge(0, 2); |
| 78 | + g.addEdge(1, 3); |
| 79 | + g.addEdge(3, 4); |
| 80 | + g.addEdge(4, 5); |
| 81 | + g.addEdge(5, 6); |
| 82 | + |
| 83 | + g.printVertexCover(); |
| 84 | + |
| 85 | + return 0; |
| 86 | +} |
0 commit comments