#include<iostream>
#include<cmath>
#include<vector>
#include <algorithm>
#include <utility>
#include <boost/graph/graph_traits.hpp>
#include <boost/graph/adjacency_list.hpp>
#include <boost/graph/subgraph.hpp>
#define k 2
using namespace std;
using namespace boost;
typedef adjacency_list_traits<vecS, vecS, directedS> Traits;
typedef subgraph< adjacency_list<vecS, vecS, directedS,
property<vertex_color_t, int>, property<edge_index_t, int> > > Graph;
typedef graph_traits<Graph>::vertex_iterator vertex_iter;
typedef pair<int, int> Edge;
typedef property_map<Graph, vertex_index_t>::type IndexMap;
vector<int> compress(vector <int>, Graph, int);
int main()
{
enum{u,v,w,x,y,z,n};
const int num_vertices= n;
Graph g(num_vertices),gcopy;
int i;
Edge edge_array[]= { Edge(u,w), Edge(v,w), Edge(v,z), Edge(z,y), Edge(w,x) }; //array of edges
const int num_edges= sizeof (edge_array)/sizeof(edge_array[0]);
for (int i = 0; i < num_edges; ++i)
add_edge(edge_array[i].first, edge_array[i].second, g); //adding the edges to the main graph
IndexMap index = get(vertex_index, g);
pair<vertex_iter, vertex_iter> vp;
vector<int> vccopy,vc;
vp=vertices(g);
vertex_iter first= vp.first;
gcopy= g.create_subgraph( ); // create a subgraph
for (vp = vertices(g),i=0; vp.first != vp.second; i++, ++vp.first)// iterates as many times as the vertics.
{
add_vertex(i, gcopy); //add thevertices one by one to G[i]
vc=compress( vccopy, gcopy, i); //k size vc foundfor G[i], if it exists.
vccopy= vc;
vccopy.push_back(index[*vp.first]); // add the i+1th vertex to the make it the k+1 size vc of G[i+1]
}
if(vc.empty())
{
cout<<"No vertex cover exists.";
}
else
{
cout<<"Vertex cover is:";
for(i=0 ; i<vc.size(); i++)
{
cout<<vc[i];
}
}
}
bool contains(vector<int> a, int item)
{
if(find(a.begin(), a.end(), item)!=a.end())
return true;
else
return false;
}
vector<int> compress( vector <int> vccopy, Graph gcopy, int j)
{
vector<int> cdd, cd0,cd1, null;
IndexMap index = get(vertex_index, gcopy);
for(int i=1; i<pow(2, j+1); i++)
{
int shift= j, icopy=i;
pair<vertex_iter, vertex_iter> vp;
graph_traits<Graph>::edge_iterator ei, ei_end;
for ( vp = vertices(gcopy); vp.first != vp.second; ++vp.first)
{
if(icopy%2==0)
{
cd0.push_back(index[*vp.first]);
}
else
{
cd1.push_back(index[*vp.first]);
}
icopy/=2; //shift right operation.
}
for (tie(ei, ei_end) = edges(gcopy); ei != ei_end; ++ei)
{ Construction of the Graph
if(contains(cd0,index[source(*ei, gcopy)]) || contains(cd0,index[target(*ei, gcopy)]))
{
break;
}
else if(contains(cd0,index[source(*ei, gcopy)]))
{
cdd.push_back(index[target(*ei, gcopy)]);
}
else if(contains(cd0,index[target(*ei, gcopy)]))
{
cdd.push_back(index[source(*ei, gcopy)]);
}
}
if ((cdd.size()+cd1.size())<=k)
{
cdd.insert(cdd.end(), cd1.begin(), cd1.end());
return cdd;
}
else
return null;
}
}