#include <assert.h>
#include <ctype.h>
#include <stdlib.h>
#include <stdio.h>
#include <limits.h>

#include <functional>

#include "util.hh"
#include "instance.hh"
#include "folding.hh"
#include "vertex.hh"
#include "vertexcover.hh"

// Helper function. Returns true if a string consiststs solely of spaces.
bool emptyline(const char* s) {
  while (*s) {
    if (!isspace(*s)) return false;
    s++;
  }

  return true;
}

// Helper function. Read lines from input file until the first line that is
// neither a comment, nor empty, nor entirely made of spaces.
char* readNextLine(FILE* f) {
  char *line = NULL;
  size_t len = 0;
  ssize_t nread;

  while ((nread = getline(&line, &len, f)) != -1) {
    // Filter empty lines.
    if (emptyline(line)) continue;

    // Filter lines that are comments.
    if (line[0] == 'c') continue;
    
    return line;
  }

    free(line);
  return NULL;
}

Instance::Instance(unsigned nVertices) :
  m_nVertices(nVertices),
  m_vertices(new Vertex[nVertices + 1]) {
}

Instance::Instance(const Instance& o) :
  m_nVertices(o.m_nVertices),
  m_vertices(new Vertex[o.m_nVertices + 1]) {
  for (unsigned v = 1; v <= m_nVertices; v++)
    m_vertices[v] = o.m_vertices[v];
}

Instance::~Instance() {
  delete [] m_vertices;
}

void Instance::insertEdge(unsigned u, unsigned v) {
  // Insert v into u's edge set.
  m_vertices[u].insertVertex(v);

  // If not a loop, insert u into v's edge set as well.
  if (u != v)
    m_vertices[v].insertVertex(u);
}

void Instance::removeEdge(unsigned u, unsigned v) {
  m_vertices[u].removeVertex(v);

  // If not a loop, then remove the symmetric edge as well.
  if (u != v)
    m_vertices[v].removeVertex(u);
}

bool Instance::hasEdge(unsigned u, unsigned v) const {
  return m_vertices[u].hasNeighbour(v);
}

const Vertex& Instance::getVertex(unsigned v) const {
  assert( v > 0 && v <= m_nVertices);
  
  return m_vertices[v];
}

void Instance::isolateVertex(unsigned v) {
  // Keep removing the first vertex while also removing v from that vertex's
  // edge list.
  while (!m_vertices[v].empty()) {
    const unsigned u = m_vertices[v].front();
    if (u != v)
      m_vertices[u].removeVertex(v);
    m_vertices[v].pop_front();
  }
}

void Instance::isolateVertex(unsigned v, list<unsigned>& changes) {
  while (!m_vertices[v].empty()) {
    const unsigned u = m_vertices[v].front();
    if (u != v) {
      m_vertices[u].removeVertex(v);
      changes.push_back(u);
    }
    m_vertices[v].pop_front();
  }    
}

void Instance::isolateVertices(const list<unsigned>& vs) {
  for (list<unsigned>::const_iterator v = vs.begin(); v != vs.end(); v++)
    isolateVertex(*v);
}

void Instance::isolateVertices(const list<unsigned>& vs,
                               list<unsigned>& changes) {
  for (list<unsigned>::const_iterator v = vs.begin(); v != vs.end(); v++)
    isolateVertex(*v, changes);
}

void Instance::getLoops(list<unsigned>& loops) const {
  loops.clear();
  
  for (unsigned v = 1; v <= m_nVertices; v++) {
    if (hasEdge(v, v))
      loops.push_back(v);
  }
}

void Instance::getIsolatedVertices(list<unsigned>& iso) const {
  iso.clear();
  
  for (unsigned v = 1; v <= m_nVertices; v++)
    if (m_vertices[v].empty())
      iso.push_back(v);

}

unsigned Instance::maxDegreeVertex() const {
  unsigned max = 0;
  unsigned maxV = 1;
  for (unsigned v = 1; v <= m_nVertices; v++) {
    if (m_vertices[v].size() > max) {
      max = m_vertices[v].size();
      maxV = v;
    }
  }
  assert(maxV != 0);
  return maxV;
}

unsigned Instance::maxDegree() const {
  return m_vertices[maxDegreeVertex()].size();
}

unsigned Instance::maxDegreeNeighbour(unsigned v) const {
  assert(!m_vertices[v].empty());

  unsigned max = 0; // All neighbours have degree at least 1.
  unsigned maxN = 0; 
  const Vertex& vr = m_vertices[v]; 
  for (Vertex::const_iterator i = vr.begin(); i != vr.end(); i++) {
    if (m_vertices[*i].size() > max) {
      max = m_vertices[*i].size();
      maxN = *i;
    }
  }

  assert(maxN != 0);
  return maxN;
}

unsigned Instance::minDegreeVertex() const {
  unsigned min = m_nVertices;
  unsigned minV = 1;
  for (unsigned v = 1; v <= m_nVertices; v++) {
    if (m_vertices[v].size() < min) {
      min = m_vertices[v].size();
      minV = v;
    }
  }
  assert(min != m_nVertices);
  return minV;
}

unsigned Instance::minDegree() const {
  return m_vertices[minDegreeVertex()].size();
}

void Instance::getMinMaxDegreeVertices(unsigned& minV, unsigned& maxV) const {
  unsigned min = getNVertices();
  unsigned max = 0;
  minV = 0; maxV = 0;

  for (unsigned v = 1; v <= getNVertices(); v++) {
    const unsigned d = m_vertices[v].size();
    if (d < min) {
      min = d;
      minV = v;
    }
    if (d > max) {
      max = d;
      maxV = v;
    }
  }
  assert(minV != 0);
  assert(maxV != 0);
}

void Instance::getNonIsoMinMaxDegreeVertices(unsigned& minV,
                                             unsigned& maxV) const {
  unsigned min = getNVertices();
  unsigned max = 0;
  minV = 0; maxV = 0;

  // Pass 1: find minimum degree vertex, and maximum vertex degree.
  for (unsigned u = 1; u <= getNVertices(); u++) {
    const unsigned d = m_vertices[u].size();
    if (d == 0) continue;
    if (d < min) {
      min = d;
      minV = u;
    }
    if (d > max) {
      max = d;
    }
  }

  // No vertices found? -> done.
  if (max == 0) return;

  // Among all vertices with maximum degree, find the one with the lowest
  // number of edges between its neighbours.
  unsigned minNBEdges = UINT_MAX;
  for (unsigned u = 1; u <= getNVertices(); u++) {
    const Vertex& U = getVertex(u);
    if (U.size() != max) continue;

    unsigned nbEdges = 0;
    for (auto v = U.begin(); v != U.end(); v++) {
      for (auto w = v; w != U.end(); w++) {
        if (hasEdge(*v, *w)) nbEdges++;
      }
    }
    if (nbEdges < minNBEdges) {
      maxV = u;
      minNBEdges = nbEdges;
    }
  }
}

bool Instance::regular() const {
  unsigned long d = m_vertices[1].size();

  for (unsigned v = 2; v <= m_nVertices; v++)
    if (m_vertices[v].size() != d)
      return false;
  
  return true;
}

unsigned Instance::findDegree2Vertex() const {
  for (unsigned v = 1; v <= m_nVertices; v++)
    if (getVertex(v).hasDegree2())
      return v;

  return 0;
}

unsigned Instance::getNEdges() const {
  // Sum up total size of all edge lists.
  unsigned total = 0;
  for (unsigned v = 1; v <= m_nVertices; v++)
    total += m_vertices[v].size();
  //fprintf(stderr, "total number of edges including symmetry: %u\n", total);

  // Count loops.
  unsigned loops = 0;
  for (unsigned v = 1; v <= m_nVertices; v++) {
    if (hasEdge(v, v)) loops++;
  }
  //fprintf(stderr, "total number of loops: %u\n", loops);

  assert((total - loops) % 2 == 0);
  return ((total - loops) / 2) + loops;
}

void Instance::getEdges(list<pair<unsigned, unsigned> >& e) const {
  e.clear();

  for (unsigned v = 1; v <= m_nVertices; v++) {
    for (Vertex::const_iterator i = m_vertices[v].begin();
	 i != m_vertices[v].end() && *i <= v; i++)
      e.push_back(pair<unsigned, unsigned>(v, *i));
  }
}

void Instance::getOpenNeighbourhood(const list<unsigned>& vs,
                                    list<unsigned>& N) const {
  // TODO: If vs is sorted, it can be made even faster by using sorted_diff().
  if (vs.empty()) return;
  auto v = vs.begin();
  N = getVertex(*v);
  v++;

  while (v != vs.end()) {
    sorted_merge_unique(N, getVertex(*v));
    v++;
  }
  for (auto v = vs.begin(); v != vs.end(); v++)
    N.remove(*v);
}

void Instance:: getClosedNeighbourhood(const list<unsigned>& vs,
                                       list<unsigned>& N) const {
  N = vs;
  for (auto v = vs.begin(); v != vs.end(); v++) {
    sorted_merge_unique(N, getVertex(*v));
  }
}

void Instance::removeLoops(VertexCover& vc) {
  list<unsigned> loops;
  getLoops(loops);

  vc.add(loops);

#ifndef NDEBUG
  loopReductions += loops.size();
#endif
  
  for (list<unsigned>::const_iterator v = loops.begin(); v != loops.end(); v++)
    isolateVertex(*v);
}

void Instance::reduceDegree1(unsigned v, VertexCover& vc,
                             list<unsigned>& chs) {
  if (m_vertices[v].hasDegree1()) {
    //fprintf(stderr, "Vertex %u has degree 1\n", v);
    const unsigned neighbour = m_vertices[v].front();
    //fprintf(stderr, "Removing its neighbour %u from the graph\n", neighbour);
    vc.add(neighbour);
    chs.insert(chs.end(), m_vertices[neighbour].begin(),
	       m_vertices[neighbour].end());
    isolateVertex(neighbour);
#ifndef NDEBUG
    deg1Reductions++;
#endif // NDEBUG
  }
}

void Instance::reduceDegree2(unsigned u, VertexCover& vc,
                             Foldings& folds, list<unsigned>& chs) {
  if (!m_vertices[u].hasDegree2()) return;
  const unsigned v = m_vertices[u].front();
  const unsigned w = m_vertices[u].back();
  const Vertex& V = getVertex(v);
  const Vertex& W = getVertex(w);  
  //fprintf(stderr, "Vertex %u has degree 2\n", u);
  //fprintf(stderr, "The neighbours are %u and %u\n", v, w);
  
  if (hasEdge(v, w)) {
    //fprintf(stderr, "%u and %u are connected\n", v, w);
    
    // Isolate u. Add v's and w's neighbourhoods to chs. Add v and w to
    // solution. Isolate v and w.
    isolateVertex(u);
    chs.insert(chs.end(), V.begin(), V.end());
    chs.insert(chs.end(), W.begin(), W.end());
    vc.add(v);
    vc.add(w);
    isolateVertex(v);
    isolateVertex(w);
#ifndef NDEBUG
    deg2ConnReductions++;
#endif
  } else {
    // Replace u's neighbours with those of v and w (w/o u, v and w of
    // course). TODO: this can probably be done a bit faster by not using the
    // utility functions like isolateVertex() but directly accessing the
    // adjacency lists of u, v and w.
    //
    // Empty u's adjacency list (this will also remove u from the adj lists of v
    // and w).
    isolateVertex(u);
    // Set u's adj list to a union of those of v and w.
    m_vertices[u].insert(m_vertices[u].end(), V.begin(), V.end());
    sorted_merge_unique(m_vertices[u], W);
    // Remove v and w from the graph.
    isolateVertex(v);
    isolateVertex(w);
    // Connect u to its new neighbours.
    for (auto i = m_vertices[u].begin(); i != m_vertices[u].end(); i++)
      m_vertices[*i].insertVertex(u);
    
    // Mark changed nodes. v and w are isolated now so they don't merit further
    // attention.
    chs.push_back(u);
    chs.insert(chs.end(), m_vertices[u].begin(), m_vertices[u].end());

    // Add fold to the front of folds to make unfolding possible.
    folds.add(new Deg2Folding(u, v, w));

#ifndef NDEBUG
    deg2Folds++;
#endif
  }
}

// Helper function. Given a vertex U with degree 3 and two of its neighbours v
// and w, return the third neighbour of U.
unsigned get3rdNeighbour(const Vertex& U, unsigned v, unsigned w) {
  assert(U.size() == 3);
  
  auto n = U.begin();
  if (*n == v || *n == w) {
    n++;
    if (*n == v || *n == w)
      n++;
  }
  assert(*n != v && *n != w);

  return *n;
}

// u has degree 3, with neighbours v, w and x. If v and w are connected
// (i.e. u, v, w form a triangle), and w has degree 3, such that x and the
// third neighbour y of w are connected, then return v. Otherwise, return 0.
unsigned reduceDegree3Helper(const Instance& g,
			     unsigned u, unsigned v, unsigned w, unsigned x) {
  // Simple tests.
  if (!g.hasEdge(v, w)) return 0;

  const Vertex& W = g.getVertex(w);
  if (W.size() != 3) return 0;
  
  // Find third neighbour y of w.
  const unsigned y = get3rdNeighbour(W, u, v);

  // x and y must be distinct.
  if (x == y) return 0;

  // Return true if edge {x, y} exists.
  if (g.hasEdge(x, y))
    return v;

  // Special case: there is no edge {x, y}, but y has degree 3, and x and y
  // have a common neighbour b. The third neighbour a of y also has degree 3,
  // and {y, a, b} form a triangle, i.e. edge {a, b} exists. The third
  // neighbour z of a is also a neighbour of v. Then, we can add v to the
  // solution. (Proof: use x). Special special case: if v has degree 3, then
  // add w to the solution.
  const Vertex& Y = g.getVertex(y);
  if (Y.size() != 3) return 0;

  const unsigned b = Y.commonNeighbour(g.getVertex(x));
  if (b == 0) return 0;

  const unsigned a = get3rdNeighbour(Y, w, b);
  const Vertex& A = g.getVertex(a);
  if (A.size() != 3) return 0;
  if (!g.hasEdge(a, b)) return 0;
  
  const unsigned z = get3rdNeighbour(A, y, b);
  if (!g.hasEdge(z, v)) return 0;

  if (g.getVertex(v).size() == 3)
    return w;
  else
    return v;
}

unsigned Instance::findDegree3Reduction(unsigned u) const {
  const Vertex& U = getVertex(u);
  
  if (U.size() != 3) return 0;
  
  // Find neighbours. 
  auto i = U.begin();
  const unsigned n1 = *(i++);
  const unsigned n2 = *(i++);
  const unsigned n3 = *i;

  unsigned r;
  if ((r = reduceDegree3Helper(*this, u, n1, n2, n3)) != 0)
    return r;
  
  if ((r = reduceDegree3Helper(*this, u, n1, n3, n2)) != 0)
    return n1;

  if ((r = reduceDegree3Helper(*this, u, n2, n1, n3)) != 0)
    return r;
  
  if ((r = reduceDegree3Helper(*this, u, n2, n3, n1)) != 0)
    return r;

  if ((r = reduceDegree3Helper(*this, u, n3, n1, n2)) != 0)
    return r;
  
  if ((r = reduceDegree3Helper(*this, u, n3, n2, n1)) != 0)
    return r;

  return 0;
}

void Instance::reduceDegree3(unsigned u, VertexCover& vc,
			     list<unsigned>& chs) {
  const unsigned v = findDegree3Reduction(u);
  if (v != 0) {
    vc.add(v);
    chs.insert(chs.end(), getVertex(v).begin(), getVertex(v).end());
    isolateVertex(v);
#ifndef NDEBUG
    deg3Reductions++;
#endif
  }
}

void Instance::reduceBuss(unsigned v, unsigned k, VertexCover& vc,
                          list<unsigned>& chs) {
  if (m_vertices[v].size() > k) {
    //fprintf(stderr, "Buss: vertex %u has degree %lu, maximum is %u, removing\n",
    //        v, m_vertices[v].size(), k);
    vc.add(v);
    chs.insert(chs.end(), m_vertices[v].begin(), m_vertices[v].end());
    isolateVertex(v);
#ifndef NDEBUG
    bussReductions++;
#endif
  }
}
  
bool Instance::checkTwins(unsigned u, unsigned v) const {
  // Special cases.
  if (u == v) return false;
  
  const Vertex& ur = m_vertices[u];
  const Vertex& vr = m_vertices[v];

  // Special case.
  if (ur.empty()) return false;
  if (vr.empty()) return false;
  
  Vertex::const_iterator i, j;
  j = vr.begin();

  // This only works because vertex neighbour lists are sorted.
  for (i = ur.begin(); i != ur.end(); i++) {
    if (*i == v) continue;
    while (j != vr.end() && *j != *i)
      j++;
    if (j == vr.end()) return false;
  }

  // TODO: this ought be be done faster
  return vr.hasNeighbour(u);
}

void Instance::reduceTwins(const list<unsigned>& vs, VertexCover& vc,
                           list<unsigned>& chs) {
  for (list<unsigned>::const_iterator u = vs.begin(); u != vs.end(); u++) {
    const list<unsigned> n = getVertex(*u);
    for (list<unsigned>::const_iterator v = n.begin(); v != n.end(); v++) {
      if (checkTwins(*u, *v)) {
        vc.add(*v);
        chs.insert(chs.end(), getVertex(*v).begin(), getVertex(*v).end());
        isolateVertex(*v);
#ifndef NDEBUG
        twinReductions++;
#endif  // NDEBUG
        continue;
      }
      if (checkTwins(*v, *u)) {
        vc.add(*u);
        chs.insert(chs.end(), n.begin(), n.end());
        isolateVertex(*u);
#ifndef NDEBUG
        twinReductions++;
#endif // NDEBUG
        break;
      }
    }
  }
}

void Instance::reduceTwins(VertexCover& vc) {
  assert(vc.empty());

  for (unsigned u = 1; u <= m_nVertices; u++) {
    if (m_vertices[u].empty()) continue;
    const list<unsigned> n = m_vertices[u];
    for (Vertex::const_iterator v = n.begin(); v != n.end(); v++) {
      // If u is a lesser twin of v, than v is part of the
      // solution.
      if (checkTwins(u, *v)) {
	vc.add(*v);
	isolateVertex(*v);
      }
    }
  }
}

void Instance::reduceUnconfined(unsigned v, VertexCover& vc,
                                list<unsigned>& chs) {
  // First check if v is uncovered. 
  list<unsigned> S; S.push_back(v);
  // Open neighbourhood of S.
  list<unsigned> NSo = getVertex(v);
  // Closed neighbourhood of S.
  list<unsigned> NSc = NSo; sorted_insert_unique(NSc, v);
  do {
    // Find a vertex u \in N(S) such that |N(u) \cap S| = 1 and |N(u) \ N[S]|
    // is minimized.
    unsigned u = 0;
    unsigned mindiff = UINT_MAX;
    unsigned w = 0;
    for (auto i = NSo.begin(); i != NSo.end(); i++) {
      // TODO: If S is sorted, then counting common elements with I is
      // faster. I tried this, and the cost of keeping S sorted outweighed the
      // gains. 
      const Vertex& I = getVertex(*i);
      // Check the size of N(i) \cap S.
      unsigned x = 0;
      for (auto j = S.begin(); j != S.end(); j++) {
        if (I.hasNeighbour(*j)) {
          x++;
          if (x > 1) break;
        }
      }
      // If |N(i) \cap S| != 1, then try the next vertex.
      if (x != 1) continue;

      // Compute N(i) \ N[S].
      list<unsigned> diffset = getVertex(*i);
      sorted_diff(diffset, NSc);

      // If diffset has size 0, then we cannot find a smaller diffset, and v
      // is unconfined.
      if (diffset.empty()) {
        vc.add(v);
        chs.insert(chs.end(), getVertex(v).begin(), getVertex(v).end());
        isolateVertex(v);
#ifndef NDEBUG
        unconfinedReductions++;
#endif // NDEBUG
        return;
      }

      // If diffset has size smaller than mindiff, then i becomes our new
      // candidate for u, and we set mindiff to |diffset|.
      if (diffset.size() < mindiff) {
        u = *i;
        mindiff = diffset.size();
        if (mindiff == 1)
          w = diffset.front();
      }
    }
    // If we could not find a vertex u, then v is not unconfined.
    if (u == 0) {
      return;
    }
    assert(mindiff != UINT_MAX);
    // If mindiff is >1, then v is not unconfined.
    if (mindiff > 1)
      return;

    // Mindiff has size 1. Find w, add it to S, adjust NSo(S) and NSc(S),
    // continue.
    assert(mindiff == 1);
    assert(w != 0);
    assert(u != 0);
    S.push_back(w);
    sorted_merge_unique(NSo, getVertex(w));
    sorted_merge_unique(NSc, getVertex(w));
    sorted_insert_unique(NSc, w);
  } while (true);
}

bool Instance::checkDuo(unsigned u, unsigned v) const {
  // Simple checks.
  if (u == v) return false;

  const Vertex& U = getVertex(u);
  if (U.size() != 3) return false;

  const Vertex& V = getVertex(v);
  if (V.size() != 3) return false;

  // Check if N(u) = N(v).
  for (auto i = U.begin(), j = V.begin(); i != U.end() && j != V.end();
       i++, j++) {
    if (*i != *j) return false;
  }
  return true;
}

bool Instance::reduceFunnel(unsigned u, Foldings& folds, list<unsigned>& chs) {
  const Vertex& U = getVertex(u);

  // TODO: Use Hua's counting trick for speedup.
  for (auto vi = U.begin(); vi != U.end(); vi++) {
    list<unsigned> Nu = U;
    unsigned v = *vi;
    Nu.remove(v);

    // Check if Nu induces a funnel.
    bool isFunnel = true;
    for (auto x = Nu.begin(); x != Nu.end(); x++) {
      const Vertex& X = getVertex(*x);
      auto z = X.begin();
      for (auto y = x; y != Nu.end(); y++) {
        if (*x == *y) continue;
        while (z != X.end() && *z < *y)
          z++;
        if (z == X.end() || *z != *y) {
          isFunnel = false;
          break;
        }
      }
      if (!isFunnel) break;
    }
    if (isFunnel) {
      // We found a funnel u, *v. We remove u and v from the graph, and add
      // edges between every two non-adjacent vertices x \in N(u) \ N[v] and y
      // \in N(v) \ N[u].
      // TODO: move into function removeAlternatives() for common
      // functionality with reduceDesk().
      list<unsigned> Nv = getVertex(v);
      // Intersection N(u) \cap N(v).
      list<unsigned> Suv;
      U.commonNeighbours(getVertex(v), Suv);
      sorted_diff(Nu, Suv);
      sorted_diff(Nv, Suv);
      Nv.remove(u);

      for (auto x = Nu.begin(); x != Nu.end(); x++) {
        sorted_merge_unique(m_vertices[*x], Nv);
      }
      for (auto x = Nv.begin(); x != Nv.end(); x++) {
        sorted_merge_unique(m_vertices[*x], Nu);
      }

      // fprintf(stderr, "Funnel folding u = %u and v = %u\n", u, *v);
      // fprintf(stderr, "N(u): ");
      // print_list(stderr, getVertex(u));
      // fprintf(stderr, "N(v): ");
      // print_list(stderr, getVertex(*v));
      // fprintf(stderr, "N(u) \\cap N(v): ");
      // print_list(stderr, Suv);
      // fprintf(stderr, "N(u) \\ N[v]: ");
      // print_list(stderr, Nu);
      // fprintf(stderr, "N(v) \\ N[u]: ");
      // print_list(stderr, Nv);
      
      isolateVertex(u, chs);
      isolateVertex(v, chs);
      isolateVertices(Suv, chs);

      folds.add(new FunnelFolding(u, v, Suv, Nv));

#ifndef NDEBUG
      funnelFolds++;
      funnelFoldIntersects += Suv.size();
#endif      
      return true;
    }
  }
  return false;
}

bool Instance::reduceDesk(unsigned u, Foldings& folds, list<unsigned>& chs) {
  // Only makes sense for degree 3 or 4 vertices.
  const Vertex& U = getVertex(u);
  // u has at most degree 4 as it cannot have no more than 2 neighbours
  // outside the cycle. The same holds true for v, x and y.
  if (U.size() < 3 || U.size() > 4) return false;

  // Iterate over all pairs {x, y} \in N(u) x N(u).
  // TODO: We can probably make this faster by first gathering the neighbours
  // of U with degree <= 4.
  for (auto x = U.begin(); x != U.end(); x++) {
    const Vertex& X = getVertex(*x);
    if (X.size() < 3 || X.size() > 4) continue;
    for (auto y = x; y != U.end(); y++) {
      if (*x == *y) continue;
      const Vertex& Y = getVertex(*y);
      if (Y.size() < 3 || Y.size() > 4) continue;

      // If x and y are adjacent, the cycle would not be chordless. TODO: this
      // can probably be done faster.
      if (hasEdge(*x, *y)) continue;
      
      // Find common neigbours of x and y.
      list<unsigned> vs;
      X.commonNeighbours(Y, vs);
      for (auto v = vs.begin(); v != vs.end(); v++) {
        // Skip u, which is always a common neighbour.
        if (*v == u) continue;
        const Vertex& V = getVertex(*v);
        if (V.size() < 3 || V.size() > 4) continue;

        // Make sure v and u are not adjacent. TODO: can probably be made
        // smarter?
        if (hasEdge(u, *v)) continue;
        
        // Now we have a chordless 4-cycle (u, x, v, y). Keep A and B sorted.
        list<unsigned> A;
        if (u < *v) {
          A.push_back(u); A.push_back(*v);
        } else {
          A.push_back(*v); A.push_back(u);
        }
        list<unsigned> B;
        if (*x < *y) {
          B.push_back(*x); B.push_back(*y);
        } else {
          B.push_back(*y); B.push_back(*x);
        }

        // Compute open neighbourhoods of A and B.
        list<unsigned> NA, NB;
        getOpenNeighbourhood(A, NA);
        getOpenNeighbourhood(B, NB);

        // Compute N(A) \cap N(B). If it is not empty, this is not a desk.
        list<unsigned> NAandNB;
        sorted_intersect(NAandNB, NA, NB);
        if (!NAandNB.empty()) continue;

        // Compute N(A) \ B and N(B) \ A.
        sorted_diff(NA, B);
        if (NA.size() > 2) continue;
        sorted_diff(NB, A);
        if (NB.size() > 2) continue;

        for (auto i = NA.begin(); i != NA.end(); i++) {
         sorted_merge_unique(m_vertices[*i], NB);
        }
        for (auto i = NB.begin(); i != NB.end(); i++) {
         sorted_merge_unique(m_vertices[*i], NA);
        }

        // Extract values from iterators that might get invalidated during
        // vertex isolation.
        const unsigned a1 = u, a2 = *v, b1 = *x, b2 = *y;

        // Isolate vertices and add folding.
        isolateVertices(A, chs);
        isolateVertices(B, chs);

        folds.add(new DeskFolding(a1, a2, b1, b2, NB));

#ifndef NDEBUG
        deskFolds++;
#endif
        return true;
      }
    }
  }
  return false;
}

void Instance::maximalMatchingUnmatchedVertices(unsigned* const mc) const {
  // mc[v] == 0 if a vertex is matched, 1 if a vertex is undecided, and 2 if
  // it is definitely unmatched.

  // We set isolated vertices to 'matched' here, as they will never help with
  // crowns.
  for (unsigned v = 1; v <= m_nVertices; v++) {
    mc[v] = m_vertices[v].empty() ? 0 : 1;
  }

  do {
    // Find an undecided vertex u with the highest degree.
    unsigned max = 0;
    unsigned u = 0;
    for (unsigned v = 1; v <= m_nVertices; v++) {
      if ((mc[v] ==  1) && m_vertices[v].size() > max) {
        max = m_vertices[v].size();
        u = v;
      }
    }
    // If we did not find a vertex with degree > 0 -> done.
    if (max == 0)
      break;

    // Find the undecided neighbour w of u with the highest degree. If we do
    // not find a such a neighbor, we mark u as unmatched.
    const Vertex& ur = getVertex(u);
    max = 0;
    unsigned w = 0;
    for (Vertex::const_iterator i = ur.begin(); i != ur.end(); i++) {
      if ((mc[*i] == 1) && m_vertices[*i].size() > max) {
        max = m_vertices[*i].size();
        w = *i;
      }
    }
    if (w == 0) {
      mc[u] = 2;
    } else {
      // Mark u and w as matched.
      mc[u] = 0;
      mc[w] = 0;
    }
  } while (true);
  
  // // Until we run out of vertices, find the next unmatched vertex, find its
  // // first unmatched neighbour, and mark both as matched.
  // for (unsigned v = 1; v <= m_nVertices; v++) {
  //   if (!mc[v]) continue;

  //   const Vertex& vr = getVertex(v);
  //   Vertex::const_iterator i;
  //   for (i = vr.begin(); i != vr.end() && !mc[*i]; i++);
  //   if (i == vr.end()) continue;
  //   mc[v] = false;
  //   mc[*i] = false;
  // }
}

// Helper function for Hopcroft-Karp. Returns true if any shortest
// augmenting paths have been found. An augmenting path is a path that starts
// at a free (unmatched) vertex, ends at a free vertex, and alternates between
// edges in and out of the matching. By definition, it goes back and forth
// between U and V, all inner vertices are matched, and 'flipping' the edges
// creates a valid matching with one more edge than the previous one. Uses a
// breadth-first-search algorithm. dist is used in the next stage of H-K as
// well.
bool findShortestAugmentingPaths(const list<unsigned>& UL,
                                 const list<unsigned>* adj, unsigned* dist,
                                 unsigned* m) {
  list<unsigned> q;   // The queue for the BFS algorithm.
  
  for (list<unsigned>::const_iterator u = UL.begin(); u != UL.end(); u++) {
    // Is *u still free?
    if (m[*u] == 0) {
      // Start searching at u.
      dist[*u] = 0;
      q.push_back(*u);
    } else {
      dist[*u] = UINT_MAX;
    }
  }
  dist[0] = UINT_MAX;
  while (!q.empty()) {
    const unsigned u = q.front();
    q.pop_front();
    if (dist[u] < dist[0]) {
      for (list<unsigned>::const_iterator v = adj[u].begin(); v != adj[u].end(); v++) {
        assert(*v != 0);
        if (dist[m[*v]] == UINT_MAX) {
          dist[m[*v]] = dist[u] + 1;
          q.push_back(m[*v]);
        }
      }
    }
  }
  
  return (dist[0] != UINT_MAX);
}

bool findMaximalSetOfASP(unsigned u, const list<unsigned>* adj,
                         unsigned* dist, unsigned* m) {
  if (u != 0) {
    for (list<unsigned>::const_iterator v = adj[u].begin();
         v != adj[u].end(); v++) {
      if (dist[m[*v]] == dist[u] + 1) {
        if (findMaximalSetOfASP(m[*v], adj, dist, m)) {
          m[*v] = u;
          m[u] = *v;
          return true;
        }
      }
    }
    dist[u] = UINT_MAX;
    return false;
  }

  return true;
}
void Instance::findMaximumMatching(const list<unsigned>& U,
                                   const list<unsigned>* adj,
                                   unsigned* m) const {
  // This uses a variation of the Hopcroft-Karp algorithm for finding a
  // maximum matching on bipartite graphs.

  // Initialize the matching to be empty. We also initialize 0 because it is
  // used as a dummy node in the matching algorithm.
  for (unsigned v = 0; v <= m_nVertices; v++)
    m[v] = 0;

  // The Hopcroft-Karp core loop: Find all shortest augmenting paths, then find
  // a maximal set of vertex-disjoint augmenting shortest paths from
  // these. Use the latter to enlarge the matching. Repeat until no more
  // shortest augmenting paths can be found.
  unsigned* dist = new unsigned[m_nVertices + 1];
  while (findShortestAugmentingPaths(U, adj, dist, m)) {
    for (list<unsigned>::const_iterator u = U.begin(); u != U.end(); u++) {
      if (m[*u] == 0) {
        findMaximalSetOfASP(*u, adj, dist, m);
      }
    }
  }
  delete [] dist;
}

void Instance::reduceCrowns(VertexCover& vc) {
  // This is based on the algorithm provided on page 5 of [Abu-Khzam, Collins,
  // Fellows, Langston, Suters, Symons: Kernelization Algorithms for the
  // Vertex Cover Problem: Theory and Experiments], with an addition from p.71
  // in [Niedermeier: Invitation to Fixed-Parameter Algorithms].

  // Step1
  //
  // Outsiders: vertices not matched by M1 will be set to true here.
  unsigned* O = new unsigned[m_nVertices + 1];

  // Find a maximal matching, mark the unmatched vertices as outsiders.
  maximalMatchingUnmatchedVertices(O);

  // Create the graph induced by O and N(O).
  // One note: We create adjacency lists for
  // every node in O which only include neigbours not in O. We also create a
  // list version of O called OL because it is faster to iterate over.
  // TODO: it might be faster to only create the lists for vertices in OL, not
  // an empty list for every vertex.
  list<unsigned> OL;
  list<unsigned> NO;
  list<unsigned>* adj = new list<unsigned>[m_nVertices + 1];
  for (unsigned u = 1; u <= m_nVertices; u++) {
    assert(O[u] != 1);
    if (!O[u]) continue;
    assert(O[u] == 2);
    OL.push_back(u);
    // TODO: use sorted_merge_unique() to build NO as NO=N(O).
    for (Vertex::const_iterator i = m_vertices[u].begin();
         i != m_vertices[u].end(); i++) {
      // There must not be any edges between nodes in O because otherwise the
      // matching O is based on would not be maximal.
      assert(!O[*i]);
      if (!O[*i]) {
        adj[u].push_back(*i);
        NO.push_back(*i);
      }
    }
    //fprintf(stderr, "adj[%u] = ", u);
    //print_list(stderr, adj[u]);
  }
  NO.sort(); NO.unique();
  //fprintf(stderr, "N(O): = ");
  //print_list(stderr, NO);
  
  // Step 2
  //
  // Find a maximimum matching M2 of the edges between O and N(O). M2[v] will
  // be 0 iff O[v] is false and v is not in N(O), or v was not matched,
  // otherwise it will be the index of v's matching partner.
  unsigned* M2 = new unsigned[m_nVertices + 1];
  
  findMaximumMatching(OL, adj, M2);

  // Step 3 (this is due to Niedermeier, the original version would not find a
  // crown here). If every node in N(O) is matched, then we have found a
  // crown with H := N(O) and I := O and are done.
  list<unsigned>::const_iterator n;
  for (n = NO.begin(); n != NO.end(); n++) {
    //fprintf(stderr, "%u %u\n", *n, M2[*n]);
    if (M2[*n] == 0)
      break;
  }
  if (n == NO.end()) {
    //fprintf(stderr, "All vertices in N(O) haven been matched\n");
    vc.add(NO);
    for (list<unsigned>::const_iterator u = OL.begin(); u != OL.end(); u++) {
      isolateVertex(*u);
    }
    for (list<unsigned>::const_iterator u = NO.begin(); u != NO.end(); u++) {
      isolateVertex(*u);
    }
#ifndef NDEBUG
    if (OL.size() > 0 || NO.size()) {
      crownReductions++;
      crownReductionSol += OL.size();
      crownReductionRem += NO.size();
    }
#endif
    delete [] M2;
    delete [] adj;
    delete [] O;

    return;
  }

  // Step 4. Build the set of nodes in O that are unmatched by M2.
  list<unsigned> I;
  //fprintf(stderr, "building list of unmatched outsiders\n");
  for (list<unsigned>::const_iterator u = OL.begin(); u != OL.end(); u++) {
    //fprintf(stderr, "u = %u M2[u] = %u\n", *u, M2[*u]);
    if (M2[*u] == 0)
      I.push_back(*u);
  }
  //fprintf(stderr, "I0: ");
  //print_list(stderr, I);

  // Step 5. Repeat H_n = N(I_n) and I_{n+1} = I_n \cup {N(H_n) under M2}
  // until there are no more changes between I_n and I_{n+1}.
  list<unsigned> H;
  do {
    H.clear();
    // TODO: make this faster using the neighbourhood methods.
    for (list<unsigned>::const_iterator u = I.begin(); u != I.end(); u++) {
      for (list<unsigned>::const_iterator v = m_vertices[*u].begin();
           v != m_vertices[*u].end(); v++) {
        H.push_back(*v);
      }
    }
    H.sort(); H.unique();
    //fprintf(stderr, "H: ");
    //print_list(stderr, H);

    const unsigned oldI = I.size();
    for (list<unsigned>::const_iterator u = H.begin(); u != H.end(); u++) {
      assert(M2[*u] != 0);
      I.push_back(M2[*u]);
    }
    I.sort(); I.unique();
    //fprintf(stderr, "I: ");
    //print_list(stderr, I);
    
    assert(oldI <= I.size());
    if (oldI == I.size())
      break;
  } while (true);

  vc.add(H);
  for (list<unsigned>::const_iterator u = H.begin(); u != H.end(); u++) {
    isolateVertex(*u);
  }
  for (list<unsigned>::const_iterator u = I.begin(); u != I.end(); u++) {
    isolateVertex(*u);
  }
#ifndef NDEBUG
  if (H.size() > 0 || I.size() > 0) {
    crownReductions++;
    crownReductionSol += H.size();
    crownReductionRem += I.size();
  }
#endif
  
  delete [] M2;
  delete [] adj;
  delete [] O;
}

void Instance::reduceClique(unsigned v, VertexCover& vc, list<unsigned>& chs) {
  // For each neigbour u of v...
  const Vertex& Nv = getVertex(v);
  // TODO: Make this faster by applying the clique trick as in branching case
  // 2.1.
  for (Vertex::const_iterator u = Nv.begin(); u != Nv.end(); u++) {
    for (Vertex::const_iterator w = u; w != Nv.end(); w++) {
      if (*u == *w) continue;
      if (!getVertex(*u).hasNeighbour(*w)) return;
    }
  }
  //fprintf(stderr, "%u has an %lu clique as neighbours\n", v, Nv.size());
  // Add N(v) to the solution.
  list<unsigned> tmp = Nv; // Copy N(v) to preserve references.
  vc.add(Nv);
  // Isolate N(v).
  isolateVertices(tmp, chs);
#ifndef NDEBUG
  cliqueReductions++;
  cliqueReductionSol += tmp.size();
#endif //NDEBUG
  assert(getVertex(v).hasDegree0());
}

void Instance::reduceClique(unsigned d, VertexCover& vc) {
  list<unsigned> dummy;
  
  for (unsigned v = 1; v <= getNVertices(); v++) {
    const Vertex& V = getVertex(v);
    if (V.size() >= 3 && V.size() <= d)
      reduceClique(v, vc, dummy);
  }
}

void Instance::reduceLocal(const list<unsigned>& vs, VertexCover& vc,
                           Foldings& folds) {
  list<unsigned>* changes = new list<unsigned>();  // TODO: use merge_sort_unique()?
  for (auto i = vs.begin(); i != vs.end(); i++)
    reduceDegree1(*i, vc, *changes);
  for (auto i = vs.begin(); i != vs.end(); i++)
    reduceDegree2(*i, vc, folds, *changes);
  for (auto i = vs.begin(); i != vs.end(); i++)
    reduceDegree3(*i, vc, *changes);

  while (!changes->empty()) {
    // TODO: this has worst case O(n*n*log(n)). Improve. merge_sort_unique()
    changes->sort();
    changes->unique();

    list<unsigned>* tmp = changes;
    changes = new list<unsigned>();
    for (auto i = tmp->begin(); i != tmp->end(); i++)
      reduceDegree1(*i, vc, *changes);
    for (auto i = tmp->begin(); i != tmp->end(); i++)
      reduceDegree2(*i, vc, folds, *changes);
    for (auto i = tmp->begin(); i != tmp->end(); i++)
      reduceDegree3(*i, vc, *changes);

    delete tmp;
  }
  
  delete changes;
}

void Instance::reduce(const list<unsigned>& vs, VertexCover& vc,
                      unsigned k, Foldings& folds) {
  assert(vc.empty());

  // Do not try to reduce empty vertex sets.
  if (vs.empty()) return;

  reduceLocal(vs, vc, folds);
  
  list<unsigned> changes;
  const unsigned fsize = folds.unfoldSize();
  for (unsigned v = 1; v <= m_nVertices; v++) {
    if (vc.size() + fsize < k)
      reduceBuss(v, k - vc.size() - fsize, vc, changes);
  }
  changes.sort(); changes.unique();
  
  // As long as there have been changes in the previous iteration, loop over
  // all changed vertices and reduce again.
  while (!changes.empty()) {
    // Exhaustively apply simple reduction rules to changed vertices.
    reduceLocal(changes, vc, folds);
    
    // Buss may actually apply to unchanged vertices because k - vc.size()
    // goes down. TODO: somehow make this smarter.
    changes.clear();
    for (unsigned v = 1; v <= m_nVertices; v++) {
      const unsigned fsize = folds.unfoldSize();
      if (vc.size() + fsize < k)
        reduceBuss(v, k - vc.size() - fsize, vc, changes);
    }
    changes.sort(); changes.unique();
    //fprintf(stderr, "After preproc loop: ");
    //dumpStats(stderr);
    //fprintf(stderr, "\n");
  }
}

void Instance::reduce(VertexCover& vc, unsigned k, Foldings& folds) {
  list<unsigned> vs;

  // Start with all nodes.
  for (unsigned v = 1; v <= m_nVertices; v++)
    vs.push_back(v);

  reduce(vs, vc, k, folds);
}

void Instance::preprocess(VertexCover& vc, Foldings& folds) {
  // Vertices with loops must always be part of the solution, so we can remove
  // them from the input graph. This is expensive, but will only be done once.
  assert(vc.empty());
  removeLoops(vc);
  
  //fprintf(stderr, "After loop removal: ");
  //dumpStats(stderr);
  //fprintf(stderr, "\n");

  bool changed = true;
  while (changed) {
    changed = false;

    // Use cheap reduction rules first.
    VertexCover red;
    const unsigned oldFolds = folds.size();
    reduce(red, getNVertices(), folds);
    
    //fprintf(stderr, "Simple reduction added %lu verts\n", red.size());
    //fprintf(stderr, "After reduction: ");
    //dumpStats(stderr);
    //fprintf(stderr, "\n");
    // Append to solution.
    vc.add(red);
    // Do we need another iteration?
    if (!red.empty()) changed = true;
    if (oldFolds < folds.size()) changed = true;

    // Reduce cliques.
    VertexCover cliques;
    reduceClique(4, cliques);
    vc.add(cliques);
    // if (!cliques.empty()) {
    //   fprintf(stderr, "Found %lu vertices as part of cliques\n",
    //           cliques.size());
    //   fprintf(stderr, "After cliques  : ");
    //   dumpStats(stderr);
    //   fprintf(stderr, "\n");
    // }
    if (!cliques.empty()) changed = true;

    // Reduce unconfined.
    VertexCover unconfined;
    for (unsigned u = 1; u <= getNVertices(); u++) {
      list<unsigned> tmp;
      reduceUnconfined(u, unconfined, tmp);
    }
    fprintf(stderr, "Found %lu unconfined vertices\n", unconfined.size());
    vc.add(unconfined);
    if (!unconfined.empty()) changed = true;
    
    // Remove greater twins, i.e. for all vertices u, v with N[u] \subseteq
    // N[v], put v into the solution.
    VertexCover twins;
    reduceTwins(twins);
    
    //fprintf(stderr, "Found %lu twins\n", twins.size());
    //fprintf(stderr, "After twin preprocessing: ");
    //dumpStats(stderr);
    //fprintf(stderr, "\n");
    // Append to solution.
    vc.add(twins);
    // Do we need another iteration?
    if (!twins.empty()) changed = true;

    // Reduce crowns.
    VertexCover crown;
    reduceCrowns(crown);
    //fprintf(stderr, "Found %lu vertices as part of crowns\n", crown.size());
    //print_list(stderr, crown);
    //fprintf(stderr, "After crowns  : ");
    //dumpStats(stderr);
    //fprintf(stderr, "\n");
    vc.add(crown);
    // Do we need another iteration?
    if (!crown.empty()) changed = true;

    // Check funnels.
    unsigned nFunnels = 0;
    for (unsigned u = 1; u <= getNVertices(); u++) {
      list<unsigned> tmp;
      if (reduceFunnel(u, folds, tmp))
        nFunnels++;
    }
    fprintf(stderr, "Found %u funnels\n", nFunnels);
    if (nFunnels > 0) changed = true;

    // Check desks. 
    unsigned nDesks = 0;
    for (unsigned u = 1; u <= getNVertices(); u++) {
      list<unsigned> tmp;
      if (reduceDesk(u, folds, tmp))
        nDesks++;
    }
    fprintf(stderr, "Found %u desks\n", nDesks);
    if (nDesks > 0) changed = true;
  }

  // Check duos. 
  // unsigned nDuos = 0;
  // for (unsigned u = 1; u <= getNVertices(); u++) {
  //   if (getVertex(u).size() != 3) continue;
  //   for (unsigned v = u + 1; v <= getNVertices(); v++) {
  //     if (checkDuo(u, v))
  //       nDuos++;
  //   }
  // }
  // fprintf(stderr, "Found %u duos\n", nDuos);
}

Instance* Instance::shrink(vector<unsigned>& invTransTable) const {
  // TODO: Make shrink return NULL if *this only has isolated vertices. This
  // saves a little bit in each branching leaf.
  unsigned* const transTable = new unsigned[m_nVertices + 1];

  // Build a translation table for vertex indices.
  unsigned newId = 1;
  for (unsigned v = 1; v <= m_nVertices; v++) {
    // We don't copy isolated vertices.
    if (!m_vertices[v].empty()) {
      transTable[v] = newId++;
    } else {
      transTable[v] = 0;
    }
  }
  //fprintf(stderr, "Built translation table for %u vertices, new instance will have %u vertices\n", m_nVertices, newId - 1);

  // Prepare reverse translation table
  invTransTable.resize(newId);
  for (unsigned v = 1; v <= m_nVertices; v++)
    if (transTable[v] != 0) {
      //fprintf(stderr, "translating %u --> %u\n", v, transTable[v]);
      invTransTable[transTable[v]] = v;
    }

  // Create new instance, drop isolated vertices, copy edge lists, translate
  // vertex numbers.
  Instance* shrunk = new Instance(newId - 1);
  newId = 1;
  for (unsigned v = 1; v <= m_nVertices; v++) {
    if (m_vertices[v].empty()) continue;
    for (auto i = m_vertices[v].begin(); i != m_vertices[v].end(); i++) {
      assert(transTable[*i] != 0);
      shrunk->m_vertices[newId].insertVertexUnsafe(transTable[*i]);
      assert(invTransTable[transTable[*i]] == *i);
    }
    newId++;
  }
  assert(newId - 1 == shrunk->m_nVertices);
  
  delete [] transTable;

  return shrunk;
}

unsigned Instance::greedyPacking(unsigned A[]) const {
  // TODO: make O(V+E)?
  unsigned* D = new unsigned[m_nVertices + 1];
  
  for (unsigned v = 1; v <= m_nVertices; v++) {
    D[v] = m_vertices[v].size();
    A[v] = 0;
  }
  unsigned s = 0;

  do {
    // Find a vertex v with A[v] = 0 and maximum degree.
    unsigned max = 0;
    unsigned v = 0;
    for (unsigned u = 1; u <= m_nVertices; u++) {
      if (A[u] == 0 && D[u] > max) {
	max = D[u];
	v = u;
      }
    }
    // No more vertices with degree > 0 -> done.
    if (max == 0)
      break;

    // Find neighbour w of v with A[w] with highest degree (and isolate v at
    // the same time).
    max = 0;
    unsigned w = 0;
    for (Vertex::const_iterator i = m_vertices[v].begin();
	 i != m_vertices[v].end(); i++) {
      if (A[*i] == 0 && D[*i] > max) {
	max = D[*i];
	w = *i;
      }
      D[*i]--;
    }
    assert(max > 0 && w > 0);

    // Take v and w into the vertex cover.
    A[v] = A[w] = 1;
    s += 2;

    // Isolate w.
    for (Vertex::const_iterator i = m_vertices[w].begin();
	 i != m_vertices[w].end(); i++) {
      D[*i]--;
    }
  } while (true);
  
  delete [] D;

  return s;
}

unsigned Instance::greedyPacking() const {
  unsigned* A = new unsigned[m_nVertices + 1];

  const unsigned size = greedyPacking(A);
  
  delete [] A;

  return size;
}

unsigned Instance::approxMVF(unsigned A[]) const {
  unsigned* D = new unsigned[m_nVertices + 1];
  
  for (unsigned v = 1; v <= m_nVertices; v++) {
    D[v] = m_vertices[v].size();
    A[v] = 0;
  }
  unsigned s = 0;

  // TODO: This can be made faster by first sorting all vertices by their
  // degree, and then just updating the sorting order whenever a vertex degree
  // changes. This would get rid of the pesky search loop at the beginning of
  // the main loop. Update: we tried this with std::list, and it was
  // slow. Might be fast enough when using custom-made data structures.
  do {
    // Find a vertex v with A[v] = 0 and maximum degree.
    unsigned max = 0;
    unsigned v = 0;
    for (unsigned u = 1; u <= m_nVertices; u++) {
      if (A[u] == 0 && D[u] > max) {
	max = D[u];
	v = u;
      }
    }
    // No more vertices with degree > 0 -> done.
    if (max == 0)
      break;

    // Put v into solution, increase solution size.
    A[v] = 1;
    s++;

    // Isolate v.
    for (Vertex::const_iterator i = m_vertices[v].begin();
	 i != m_vertices[v].end(); i++) {
      D[*i]--;
    }    
  } while (true);
  
  delete [] D;

  return s;
}

unsigned Instance::approxMVF() const {
  unsigned* A = new unsigned[m_nVertices + 1];

  const unsigned size = approxMVF(A);
  
  delete [] A;

  return size;
}

unsigned Instance::fracUB() const {
  unsigned* A = new unsigned[m_nVertices + 1];
  for (unsigned v = 1; v <= m_nVertices; v++)
    A[v] = 0;

  unsigned s = 0;

  // We have to go through each edge twice. The easiest way would be to simply
  // iterate over all vertice neighbours (because of the symmetry), but we don
  // not want to see the same edge twice in close succession. So we do it like
  // this.
  for (unsigned u = 1; u <= m_nVertices; u++) {
    for (Vertex::const_iterator v = m_vertices[u].begin();
	 v != m_vertices[u].end() && *v <= u; v++) {
      if (A[u] <= 1 && A[*v] <= 1) {
        A[u]++;
        A[*v]++;
        s++;
      }
    }
  }
  for (unsigned u = 1; u <= m_nVertices; u++) {
    for (Vertex::const_iterator v = m_vertices[u].begin();
	 v != m_vertices[u].end() && *v <= u; v++) {
      if (A[u] <= 1 && A[*v] <= 1) {
        A[u]++;
        A[*v]++;
        s++;
      }
    }
  }

  delete [] A;
  
  return s;
}

unsigned Instance::hLB() const {
  // Two arrays for the first and second neighbour of v. 0 means that
  // neighbour is not set. 
  unsigned* A1 = new unsigned[m_nVertices + 1];
  unsigned* A2 = new unsigned[m_nVertices + 1];
  for (unsigned v = 1; v <= m_nVertices; v++) {
    A1[v] = 0;
    A2[v] = 0;
  }

  // First, construct a subgraph by going through all edges twice and adding
  // an edge to the subgraph if neither of its vertices are part of two edges
  // that have been added already.
  // The trick here is that by going through each neighbourhood, we touch each
  // edge twice because of the symmetry of hasEdge(u, v) <-> u \in N(v) and v
  // \in N(u).
  for (unsigned u = 1; u <= m_nVertices; u++) {
    for (Vertex::const_iterator v = m_vertices[u].begin();
         v != m_vertices[u].end(); v++) {
      if (A2[u] == 0 && A2[*v] == 0) {
        if (A1[u] == 0)
          A1[u] = *v;
        else
          A2[u] = *v;
        if (A1[*v] == 0)
          A1[*v] = u;
        else
          A2[*v] = u;
      }
    }
  }

  // Repack triangles. If a vertex u and its two neighbours i and j in the
  // subgraph form a triangle in the original graph but not in the subgraph,
  // then repack them into a triangle.
  bool* F = new bool[m_nVertices + 1];
  for (unsigned u = 1; u <= m_nVertices; u++)
    F[u] = false;
  
  for (unsigned u = 1; u <= m_nVertices; u++) {
    const unsigned i = A1[u];
    const unsigned j = A2[u];

    if (i != j && i != 0 && j != 0 && !F[u] && !F[i] && !F[j] && hasEdge(i, j)) {
      // If the first neighbour of i is some unrelated node x, then remove i
      // as a neighbour from x, and replace x with j as i's first
      // neighbour. Otherwise, do the same with the second neighbour of i.
      if (A1[i] != u && A1[i] != j) {
        // If i only has one neighbour, then there is no need to replace.
        const unsigned x = A1[i];
        if (x != 0) {
          if (A1[x] == i)
            A1[x] = 0;
          else
            A2[x] = 0;
        }
        A1[i] = j;
      } else if (A2[i] != u && A2[i] != j) {
        const unsigned x = A2[i];
        if (x != 0) {
          if (A1[x] == i)
            A1[x] = 0;
          else
            A2[x] = 0;
        }
        A2[i] = j;
      }
      // Do the same for j.
      if (A1[j] != u && A1[j] != i) {
        const unsigned x = A1[j];
        if (x != 0) {
          if (A1[x] == j)
            A1[x] = 0;
          else
            A2[x] = 0;
        }
        A1[j] = i;
      } else if (A2[j] != u && A2[j] != i) {
        const unsigned x = A2[j];
        if (x != 0) {
          if (A1[x] == j)
            A1[x] = 0;
          else
            A2[x] = 0;
        }
        A2[j] = i;
      }
      F[u] = F[i] = F[j] = true;
    }
  }
  
  delete [] F;
  
  // For each path or cycle in the tmp graph, add ceil(x/2) to the lower
  // bound, where x is the number of edges in that path or cycle. A path with
  // n vertices has n-1 edges. A cycle with n vertices has n edges.
  unsigned lb = 0;
  for (unsigned u = 1; u <= m_nVertices; u++) {
    // Find first vertex with neighbors remaining.
    if (A1[u] == 0 && A2[u] == 0) continue;

    unsigned edges = 0;
    // Track u's neighbours, starting with the one in A1 if it exists. Repeat
    // until there are no more neighbours, or we hit v again (then we have a
    // cycle).
    unsigned v = u;
    while (A1[v] != 0 || A2[v] != 0) {
      unsigned next = 0;
      if (A1[v] != 0) {
        next = A1[v];
        A1[v] = 0;
      } else {
        next = A2[v];
        A2[v] = 0;
      }
      if (A1[next] == v)
        A1[next] = 0;
      else
        A2[next] = 0;
      v = next;
      edges++;
      if (v == u) break;
    }
    v = u;
    while (A1[v] != 0 || A2[v] != 0) {
      unsigned next = 0;
      if (A1[v] != 0) {
        next = A1[v];
        A1[v] = 0;
      } else {
        next = A2[v];
        A2[v] = 0;
      }
      if (A1[next] == v)
        A1[next] = 0;
      else
        A2[next] = 0;
      v = next;
      edges++;
      if (v == u) break;
    }
    lb += (edges + 1) / 2;
  }
  
  delete [] A2;
  delete [] A1;

  return lb;
}

// Helper function for findHLBApprox(). Delete vertex v from the
// subgraph consisting of the same vertices as the main graph, and of the
// edges defined by the adjacancy arrays A1 and A2: if there is an edge (u,
// v), then either A1[v] == u or A2[v] == u, and either A1[u] == v or A2[u] ==
// v. A1[v] and A2[v] can be 0 if v has only one neighbour, or n neighbours at
// all.
void deleteFromSubgraph(unsigned v, unsigned A1[], unsigned A2[]) {
  if (A1[v] != 0) {
    const unsigned tmp = A1[v];
    A1[v] = 0;
    if (A1[tmp] == v)
      A1[tmp] = 0;
    else
      A2[tmp] = 0;
  }
  if (A2[v] != 0) {
    const unsigned tmp = A2[v];
    A2[v] = 0;
    if (A1[tmp] == v)
      A1[tmp] = 0;
    else
      A2[tmp] = 0;
  }
}

int _compvert(const void* p1, const void* p2) {
  return (((int) ((const pair<unsigned, unsigned>*) p2)->second)
           - ((int) ((const pair<unsigned, unsigned>*) p1)->second));
}

// Helper to add a vertex u to the novcstack.
void addToNoVCStack(unsigned u, unsigned* A1, unsigned* A2, bool* cov, list<unsigned>& noVCStack) {
  // If u has no neighbours in the subgraph, then ignore it.
  if (A1[u] == 0 && A2[u] == 0)
    return;
  
  // Otherwise, pick any one neighbour x of u in the subgraph that is
  // not in the solution and add it to novcstack.
  bool flagset = false;
  if (A1[u] != 0 && !cov[A1[u]]) {
    //fprintf(stderr, "adding %u to novcstack because it is a neighbour of %u\n", A1[u], u);
    noVCStack.push_front(A1[u]);
    flagset = true;
  }
  if (A2[u] != 0 && !cov[A2[u]]) {
    if (!flagset || A1[A2[u]] == 0 || A2[A2[u]] == 0) {
      //fprintf(stderr, "adding %u to novcstack because it is a neighbour of %u or because this vertex will become isolated\n", A2[u], u);
      noVCStack.push_front(A2[u]);
    }
  }
}

// Helper function for findHLBApprox(): if the 2-degree connected rule applies
// to u and its neighbours v and w, then add v and w to the solution, remove
// u, v, w from g and S, and add the remaining neigbourhoods of v and w to chs
// so that they can be checked as well. And also do a lot of other stuff that
// only Hua understands...
void reduceDegree2ConnectedAndRemoveFromS(unsigned u, Instance& g, unsigned* A1, unsigned* A2, bool* cov, list<unsigned>& novcstack, list<unsigned>& chs) {
  const Vertex& U = g.getVertex(u);
  if (!U.hasDegree2()) return;
  const unsigned v = U.front();
  const unsigned w = U.back();
  if (!g.hasEdge(v, w)) return;

  //fprintf(stderr, "reduce vertex %u and use vertices %u and %u to vc\n", u, v, w);
  // Delete u from g and S, then add v and w to the solution. Add N_G(v) and
  // N_G(w) to chs, then delete v and w from g and S.
  g.isolateVertex(u);
  deleteFromSubgraph(u, A1, A2);
  cov[v] = true;
  cov[w] = true;
  chs.insert(chs.end(), g.getVertex(v).begin(), g.getVertex(v).end());
  chs.insert(chs.end(), g.getVertex(w).begin(), g.getVertex(w).end());
  
  addToNoVCStack(v, A1, A2, cov, novcstack);
  g.isolateVertex(v);
  deleteFromSubgraph(v, A1, A2);
  
  addToNoVCStack(w, A1, A2, cov, novcstack);
  g.isolateVertex(w);
  deleteFromSubgraph(w, A1, A2);

}

bool Instance::findHLBApprox(VertexCover& vc) {
  // Two arrays for the first and second neighbour of v. 0 means that
  // neighbour is not set. 
  unsigned* A1 = new unsigned[m_nVertices + 1];
  unsigned* A2 = new unsigned[m_nVertices + 1];
  for (unsigned v = 1; v <= m_nVertices; v++) {
    A1[v] = 0;
    A2[v] = 0;
  }

  // First, construct a subgraph by going through all edges twice and adding
  // an edge to the subgraph if neither of its vertices are part of two edges
  // that have been added already.
  // The trick here is that by going through each neighbourhood, we touch each
  // edge twice because of the symmetry of hasEdge(u, v) <-> u \in N(v) and v
  // \in N(u).
  for (unsigned u = 1; u <= m_nVertices; u++) {
    for (Vertex::const_iterator v = m_vertices[u].begin();
         v != m_vertices[u].end(); v++) {
      if (A2[u] == 0 && A2[*v] == 0) {
        if (A1[u] == 0)
          A1[u] = *v;
        else
          A2[u] = *v;
        if (A1[*v] == 0)
          A1[*v] = u;
        else
          A2[*v] = u;
      }
    }
  }

  
  // Repack triangles. If a vertex u and its two neighbours i and j in the
  // subgraph form a triangle in the original graph but not in the subgraph,
  // then repack them into a triangle.
  bool* F = new bool[m_nVertices + 1];
  for (unsigned u = 1; u <= m_nVertices; u++)
    F[u] = false;
  
  for (unsigned u = 1; u <= m_nVertices; u++) {
    const unsigned i = A1[u];
    const unsigned j = A2[u];

    if (i != j && i != 0 && j != 0 && !F[u] && !F[i] && !F[j] && hasEdge(i, j)) {
      // If the first neighbour of i is some unrelated node x, then remove i
      // as a neighbour from x, and replace x with j as i's first
      // neighbour. Otherwise, do the same with the second neighbour of i.
      if (A1[i] != u && A1[i] != j) {
        const unsigned x = A1[i];
        if (x != 0) {
          if (A1[x] == i)
            A1[x] = 0;
          else
            A2[x] = 0;
        }
        A1[i] = j;
      } else if (A2[i] != u && A2[i] != j) {
        const unsigned x = A2[i];
        if (x != 0) {
          if (A1[x] == i)
            A1[x] = 0;
          else
            A2[x] = 0;
        }
        A2[i] = j;
      }
      // Do the same for j.
      if (A1[j] != u && A1[j] != i) {
        const unsigned x = A1[j];
        if (x != 0) {
          if (A1[x] == j)
            A1[x] = 0;
          else
            A2[x] = 0;
        }
        A1[j] = i;
      } else if (A2[j] != u && A2[j] != i) {
        const unsigned x = A2[j];
        if (x != 0) {
          if (A1[x] == j)
            A1[x] = 0;
          else
            A2[x] = 0;
        }
        A2[j] = i;
      }
      F[u] = F[i] = F[j] = true;
    }
  }
  
  delete [] F;

  // Make sure all nodes are in the subgraph.
  for (unsigned u = 1; u <= getNVertices(); u++) {
    //fprintf(stderr, "vertex %u: A1 = %u  A2 = %u\n", u, A1[u], A2[u]);
    if (A1[u] == 0 && A2[u] == 0) {
      delete [] A2;
      delete [] A1;
      return false;
    }
    if (A1[u] == A2[u]) {
      //fprintf(stderr, "two neighbors are the same\n");
      A2[u] = 0;
    }
  }

  // Helper for faster membership test in vc during the construction phase.
  bool* cov = new bool[getNVertices() + 1];
  for (unsigned u = 1; u <= getNVertices(); u++)
    cov[u] = false;

  // Sort vertices by degree in descending order.
  pair<unsigned, unsigned>* sortvert
    = new pair<unsigned, unsigned>[getNVertices() + 1];
  for (unsigned u = 1; u <= getNVertices(); u++) {
    sortvert[u].first = u;
    sortvert[u].second = getVertex(u).size();
  }
  qsort(sortvert + 1, getNVertices(),
        sizeof(pair<unsigned, unsigned>), _compvert);
  //fprintf(stderr, "sorted by vertex degree\n");
  // Find next vertex with degree != 0 in the subgraph. 
  for (unsigned s = 1; s <= getNVertices(); s++) {
    const unsigned u = sortvert[s].first;
    //fprintf(stderr, "Using vertex %u with degree %u, real degree %lu\n", u, sortvert[s].second, getVertex(u).size());
    
    // This can happen because vertices will be isolated.
    if (A1[u] == 0 && A2[u] == 0) continue;

    // u is part of either a cycle or a path. We find all other vertices in
    // the component to decide which one it is.
    list<unsigned> component;
    unsigned next = A1[u];
    const unsigned firstRight = A2[u];
    deleteFromSubgraph(u, A1, A2);
    bool nextToSolution;  // true if the next vertex in the component goes
                          // into the solution
    while (next != 0) {
      component.push_back(next);
      const unsigned tmp = next;
      if (A1[next] != 0) {
        assert(A2[next] == 0);
        next = A1[next];
      } else {
        next = A2[next];
      }
      deleteFromSubgraph(tmp, A1, A2);
      if (next == firstRight) break;
    }
    // If next == firstRight, then we have a circle, unless if firstRight ==
    // 0, in which case we have a path.
    if (firstRight != 0 && next == firstRight) {
      // Add firstRight and u to end of circle (yes, end of circle).
      component.push_back(firstRight);
      component.push_back(u);
      // Circles always put the larger half into vc.
      nextToSolution = true;  
      // Now, component contains all vertices in the circle in order.
      //fprintf(stderr, "found cycle in subgraph: ");
      //print_list(stderr, component);
    } else {
      // The component is a path, so we add u to the front, and continue with
      // firstRight till the end.
      component.push_front(u);
      next = firstRight;
      while (next != 0) {
        component.push_front(next);
        const unsigned tmp = next;
        if (A1[next] != 0) {
          assert(A2[next] == 0);
          next = A1[next];
        } else {
          next = A2[next];
        }
        deleteFromSubgraph(tmp, A1, A2);
      }
      // Paths of odd length don't put the first vertex into vc.
      nextToSolution = (component.size() % 2 == 0);
      //fprintf(stderr, "found path in subgraph: ");
      //print_list(stderr, component);
    }

    // Stacks for vertices that still have to be checked.
    list<unsigned> fastVCStack, vcStack, noVCStack;
    
    // We alternatingly add vertices into the component to the solution, or
    // push them onto the novcstack.
    for (list<unsigned>::const_iterator v = component.begin();
         v != component.end(); v++) {
    //for (list<unsigned>::const_iterator v = component.end();
    //     v != component.begin(); --v) {
      if (nextToSolution) {
        //fprintf(stderr, "adding %u to vc because it is in a component\n", *v);
        cov[*v] = true;
        // reduce2() all vertices in N_G(*v) which are not in N_S(*v)
        list<unsigned> chs = getVertex(*v);
        isolateVertex(*v);
        while (!chs.empty()) {
          const unsigned x = chs.front();
          chs.pop_front();
          if (A1[*v] != x && A2[*v] != x)
            reduceDegree2ConnectedAndRemoveFromS(x, *this, A1, A2, cov,
						 noVCStack, chs);
        }
        deleteFromSubgraph(*v, A1, A2);
      } else {
        //fprintf(stderr, "adding %u to novcstack because it is in a component\n", *v);
        noVCStack.push_front(*v);
      }
      nextToSolution = !nextToSolution;
    }

    //fprintf(stderr, "This is a list of novcstac: ");
    //print_list(stderr, noVCStack);
    
    // Process stacks.
    while (!fastVCStack.empty() || !vcStack.empty() || !noVCStack.empty()) {
      if (!noVCStack.empty()) {
        // Get topmost vertex that must not be in the solution.
        const unsigned v = noVCStack.front();
        noVCStack.pop_front();
	//fprintf(stderr, "Neighbors from novc vertex %u\n", v);
	//print_list(stderr, getVertex(v));
        // Add neighbourhood of v in *this to the solution, and also to
        // vcstack.
        for (auto i = getVertex(v).begin(); i != getVertex(v).end(); i++) {
          //fprintf(stderr, "adding %u to vc because its neighbour %u is not in vc\n", *i, v);
          cov[*i] = true;
          // Some vertices wil get preferential treatment.
          if (A1[*i] == 0 && A2[*i] == 0) {
            //fprintf(stderr, "%u not pushed on vcstack because it has no neighbours in S\n", *i);
            continue;
          }
          if ((A1[*i] != 0 && A2[*i] == 0) || (A1[*i] == 0 && A2[*i] != 0) ){
            //fprintf(stderr, "pushing %u onto fastvcstack because it has only one neighbour in S\n", *i);
            fastVCStack.push_front(*i);
          } else if ( (A1[A1[*i]] == 0 || A2[A1[*i]] == 0) ||
                      (A1[A2[*i]] == 0 || A2[A2[*i]] == 0)  ) {
            //fprintf(stderr, "pushing %u onto fastvcstack because one of its two neighbors will become isolated in S\n", *i);
            fastVCStack.push_front(*i);
          }
          else {
            //fprintf(stderr, "pushing %u onto normal vcstack because it has two neighbours in S\n", *i);
            vcStack.push_front(*i);
          }
        }
        // Delete v from graph and subgraph.
        isolateVertex(v);
        deleteFromSubgraph(v, A1, A2);
      }
      // Find topmost vertex on vcstack that still has neighbours in subgraph.
      while (!fastVCStack.empty() || !vcStack.empty()) {
        unsigned u;
        if (!fastVCStack.empty()) {
          u = fastVCStack.front();
          fastVCStack.pop_front();
        } else {
          u = vcStack.front();
          vcStack.pop_front();
        }
        // Always isolate u in the graph.
        // Check N_G(u) for reduce2 exhaustively; remove reduced vertices from
        // S and G.
        list<unsigned> chs = getVertex(u);
        isolateVertex(u);
        while (!chs.empty()) {
          const unsigned x = chs.front();
          chs.pop_front();
          reduceDegree2ConnectedAndRemoveFromS(x, *this, A1, A2, cov,
					       noVCStack, chs);
        }        
        // If u has no neighbours in the subgraph, then ignore it.
        if (A1[u] == 0 && A2[u] == 0)
          continue;
        // Otherwise, pick any one neighbour x of u in the subgraph that is
        // not in the solution and add it to novcstack.
	addToNoVCStack(u, A1, A2, cov, noVCStack);
        // Remove u from S, and we are done.
        deleteFromSubgraph(u, A1, A2);
        break;
      }
    }
  }

  // fprintf(stderr, "hlb cov: ");
  // // Build solution from helper.
  // for (unsigned u = 1; u <= getNVertices(); u++) {
  //   if (cov[u])
  //     fprintf(stderr, "%u, ", u);
  // }
  // fprintf(stderr, "\n");
  
  // Build solution from helper.
  for (unsigned u = 1; u <= getNVertices(); u++) {
    assert(getVertex(u).empty());
    if (cov[u])
      vc.add(u);
  }
  delete [] sortvert;
  
  delete [] cov;

  delete [] A2;
  delete [] A1;
  
  return true;
}

unsigned Instance::cliqueCoverLB() const {
  // We work as follows: vertices will be coloured with their clique number,
  // with cliques numbers starting from 0. For each clique, we keep track of
  // its current size. We iterate over all vertices in descending order of
  // their degree. For each vertex, we add it to the largest eligible clique.
  //

  // The clique color of vertex u is stored in colour[u]. A colour of UINT_MAX
  // means the vertex is in no clique yet.
  unsigned* colour = new unsigned[getNVertices() + 1];
  for (unsigned u = 1; u <= getNVertices(); u++)
    colour[u] = UINT_MAX;

  // The current number of cliques.
  unsigned nCliques = 0;
  
  // For clique c, cliqSize[c] contains the size of the clique. There are at
  // most n cliques. Clique sizes will be initialized lazily whenever a new
  // clique is created.
  unsigned* cliqueSize = new unsigned[getNVertices()]; 

  // This will be used when iterating over each vertex. For clique c,
  // cliqueNeighbours[c] contains the number of neighbours of the current
  // vertex v that are in c. This will be initialized to 0 only once
  // (here). Used entries will be reset to 0 at the end of each vertex
  // iteration to keep the complexity at O(d(v)).
  unsigned* cliqueNeighbours = new unsigned[getNVertices()];
  for (unsigned c = 0; c < getNVertices(); c++)
    cliqueNeighbours[c] = 0;

  // The local clique dictionary. When processing vertex v which has C cliques
  // in N(v), cliqueDict[c] with 0 <= c < localCliques contains the colour of
  // the cliques which contains neighbours of v. Does not need to be
  // initialized.
  unsigned* cliqueDict = new unsigned[getNVertices()];
  
  // Iterate over vertices by degree in descending order. TODO: make this
  // faster by not using std::list.
  list<pair<unsigned, unsigned> > sortedVerts;
  for (unsigned u = 1; u <= getNVertices(); u++)
    sortedVerts.push_back(pair<unsigned, unsigned>(getVertex(u).size(), u));
  sortedVerts.sort(greater<pair<unsigned int, unsigned int> >());

  for (auto v = sortedVerts.begin(); v != sortedVerts.end(); v++) {
    const Vertex& V = getVertex((*v).second);
    // fprintf(stderr, "vertex %u with degree %u (real degree %lu)\n",
    //         (*v).second, (*v).first, V.size());
    assert((*v).first == V.size());

    // The number of cliques in the neighbourhood of v. This is also the
    // number of valid entries in cliqueDict.
    unsigned localCliques = 0;
    
    // Check cliques of all neighbours
    for (auto i = V.begin(); i != V.end(); i++) {
      // Ignore uncoloured vertices
      const unsigned c = colour[*i];
      if (colour[*i] == UINT_MAX) continue;

      // Increase the number of neighbours of v in clique c by 1. If
      // this is the first neighbour in this clique, then add the clique to
      // the local clique dictionary.
      if (cliqueNeighbours[c] == 0) {
        cliqueDict[localCliques] = c;
        localCliques++;
      }
      cliqueNeighbours[c]++;
    }

    // Find the largest clique in N(v) which contains only neighbours of v.
    unsigned largestClique = UINT_MAX;
    unsigned maxCliqueSize = 0;
    for (unsigned l = 0; l < localCliques; l++) {
      const unsigned c = cliqueDict[l];
      assert(cliqueNeighbours[c] <= cliqueSize[c]);
      // Skip cliques which have vertices outside N(v).
      if (cliqueNeighbours[c] < cliqueSize[c])
        continue;
      if (cliqueSize[c] > maxCliqueSize) {
        largestClique = c;
        maxCliqueSize = cliqueSize[c];
      }
    }

    // If we have not found a viable clique for v, then create a new clique,
    // and set its membership to v. Otherwise, add v to the largest viable
    // clique.
    if (largestClique == UINT_MAX) {
      colour[(*v).second] = nCliques;
      cliqueSize[nCliques] = 1;
      nCliques++;
    } else {
      colour[(*v).second] = largestClique;
      cliqueSize[largestClique]++;
    }

    // Reset the neighbourhood counters of all local cliques to 0.
    for (unsigned c = 0; c < localCliques; c++)
      cliqueNeighbours[cliqueDict[c]] = 0;
  }

  delete [] cliqueDict;
  delete [] cliqueNeighbours;
  delete [] cliqueSize;
  delete [] colour;
  
  return (getNVertices() - nCliques);
}

unsigned Instance::findConnectedComponents(unsigned* comp) const {
  // This uses a simple breadth-first coloring algorithm.
  
  // Initialize all vertices.
  for (unsigned v = 1; v <= getNVertices(); v++)
    comp[v] = UINT_MAX;

  // Initialize next free color and first uncolored vertex.
  unsigned nextColor = 0;
  unsigned firstFreeVertex = 1;

  // Repeat until all vertices are colored.
  do {
    // Find first uncolored vertex. If there is none, we are done.
    while (firstFreeVertex <= getNVertices() &&
           comp[firstFreeVertex] != UINT_MAX)
      firstFreeVertex++;
    if (firstFreeVertex > getNVertices())
      break;

    // Initialize the queue with the first free vertex.
    list<unsigned> queue;
    queue.push_back(firstFreeVertex);

    // As long as the queue is not empty, take the first vertex, set it to the
    // current color, and add its uncolored neighbours to the queue.
    while (!queue.empty()) {
      const unsigned v = queue.front();
      queue.pop_front();

      // Alread colored? This may happen if node appears in more than one
      // neighbourhood list.
      if (comp[v] != UINT_MAX) continue;

      comp[v] = nextColor;
      for (Vertex::const_iterator i = m_vertices[v].begin();
             i != m_vertices[v].end(); i++) {
        if (comp[*i] == UINT_MAX)
          queue.push_back(*i);
      }
    }

    nextColor++;
  } while (true);

  return nextColor;
}

Instance* Instance::getComponent(const unsigned* comp, unsigned c,
                                 vector<unsigned>& invTransTable) const {
  // Build a translation table for vertex indices.
  unsigned* const trans = new unsigned[m_nVertices + 1];
  unsigned newId = 1;
  for (unsigned v = 1; v <= m_nVertices; v++) {
    // Only copy vertices in component c.
    if (comp[v] == c) {
      trans[v] = newId++;
    } else {
      trans[v] = 0;
    }
  }
  //fprintf(stderr, "Built translation table for %u vertices, new instance will have %u vertices\n", m_nVertices, newId - 1);

  // Prepare reverse translation table
  invTransTable.resize(newId);
  for (unsigned v = 1; v <= m_nVertices; v++)
    if (trans[v] != 0) {
      //fprintf(stderr, "translating %u --> %u\n", v, trans[v]);
      invTransTable[trans[v]] = v;
    }

  // Create new instance, drop vertices not in c, copy edge lists, translate
  // vertex numbers.
  Instance* shrunk = new Instance(newId - 1);
  newId = 1;
  for (unsigned v = 1; v <= m_nVertices; v++) {
    if (comp[v] != c) continue;
    for (Vertex::const_iterator i = m_vertices[v].begin(); i != m_vertices[v].end(); i++) {
      if (comp[*i] == c) {
        assert(trans[*i] != 0);
        assert(trans[v] == newId);
        shrunk->m_vertices[newId].insertVertexUnsafe(trans[*i]);
        assert(invTransTable[trans[*i]] == *i);
      }
    }
    newId++;
  }
  assert(newId - 1 == shrunk->m_nVertices);

  delete [] trans;

  return shrunk;
}

// #include <boost/graph/adjacency_list.hpp>
// #include <boost/graph/boyer_myrvold_planar_test.hpp>

// bool Instance::planar() const {
//   using namespace boost;
//   typedef adjacency_list<vecS, vecS, undirectedS,
//                          property<vertex_index_t, int> > Graph;
//   Graph g(getNVertices());
//   for (unsigned u = 1; u <= getNVertices(); u++) {
//     for (Vertex::const_iterator v = m_vertices[u].begin();
//          v != m_vertices[u].end(); v++) {
//       // Do not add edges twice.
//       if (u > *v) continue;
//       add_edge(u - 1, *v - 1, g);
//     }
//   }

//   return boyer_myrvold_planarity_test(g);
// }

void Instance::getDegreeHistogram(unsigned *hist) const {
  for (unsigned d = 0; d <= maxDegree(); d++)
    hist[d] = 0;
  
  for (unsigned u = 1; u <= m_nVertices; u++)
    hist[m_vertices[u].size()]++;
}

void Instance::dump(FILE* out) const {
  fprintf(out, "Number of vertices: %u\n", m_nVertices);
  for (unsigned v = 1; v <= m_nVertices; v++) {
    fprintf(out, "Vertex: %6u has %6lu edges: ", v, m_vertices[v].size());
    for (Vertex::const_iterator i = m_vertices[v].begin(); i != m_vertices[v].end(); i++)
      fprintf(out, "%u ", *i);
    fprintf(out, "\n");
  }
}

void Instance::dumpStats(FILE* out) const {
  list<unsigned> loops;
  getLoops(loops);
  list<unsigned> iso;
  getIsolatedVertices(iso);
  fprintf(out,
	  "#vertices: %u, #edges: %u, min d %u, max d: %u, #loops: %lu, #iso: %lu,",
	  m_nVertices, getNEdges(), m_nVertices > 0 ? minDegree() : 0, m_nVertices > 0 ? maxDegree() : 0, loops.size(), iso.size());
  // fprintf(stderr, "Degree histogram:\n");
  // unsigned* hist = new unsigned[maxDegree() + 1];
  // getDegreeHistogram(hist);
  // for (unsigned d = 0; d <= maxDegree(); d++)
  //   fprintf(stderr, "Degree %u: %u nodes\n", d, hist[d]);
  // delete [] hist;
  // for (unsigned u = 1; u <= getNVertices(); u++) {
  //   if (getVertex(u).size() == 4)
  //     fprintf(out, "%u has degree 4\n", u);
  // }
  // for (unsigned u = 1; u <= getNVertices(); u++) {
  //   if (getVertex(u).size() == 3)
  //     fprintf(out, "%u has degree 3\n", u);
  // }
}

Instance* Instance::readInstance(FILE* f) {
  int ret;
  
  // Read header.
  char* header = readNextLine(f);
  if (!header) return NULL;
  //fprintf(stderr, "header: %s\n", header);
  unsigned nVertices, nEdges;
  ret = sscanf(header, "p td %u %u", &nVertices, &nEdges);
  free(header);
  if (ret != 2) return NULL;
  fprintf(stderr, "Parsing a graph with %u vertices and %u edges\n",
          nVertices, nEdges);
  Instance* in = new Instance(nVertices);  
  
  // Read edges.
  char* edge;
  unsigned edgesRead = 0;
  while ((edge = readNextLine(f)) != NULL) {
    unsigned u, v;
    ret = sscanf(edge, "%u %u", &u, &v);
    free(edge);
    if (ret != 2)  return NULL;
    in->insertEdge(u, v);
    edgesRead++;
  }

  assert(edgesRead == nEdges);
  
  return in;
}

void Instance::write(FILE* out) const {
  fprintf(out, "p td %u %u\n", getNVertices(), getNEdges());
  for (unsigned u = 1; u <= getNVertices(); u++) {
    for (auto v = getVertex(u).begin(); v != getVertex(u).end(); v++) {
      if (*v > u)
        fprintf(out, "%u %u\n", u, *v);
    }
  }
}

#ifndef NDEBUG
unsigned long Instance::loopReductions;
unsigned long Instance::deg1Reductions;
unsigned long Instance::deg2ConnReductions;
unsigned long Instance::deg3Reductions;
unsigned long Instance::bussReductions;
unsigned long Instance::twinReductions;
unsigned long Instance::unconfinedReductions;
unsigned long Instance::crownReductions;
unsigned long Instance::crownReductionSol;
unsigned long Instance::crownReductionRem;
unsigned long Instance::cliqueReductions;
unsigned long Instance::cliqueReductionSol;

unsigned long Instance::deg2Folds;
unsigned long Instance::funnelFolds;
unsigned long Instance::funnelFoldIntersects;
unsigned long Instance::deskFolds;

void Instance::initStats() {
  loopReductions = 0;
  deg1Reductions = 0;
  deg2ConnReductions = 0;
  deg3Reductions = 0;
  bussReductions = 0;
  twinReductions = 0;
  unconfinedReductions = 0;
  crownReductions = 0;
  crownReductionSol = 0;
  crownReductionRem = 0;
  cliqueReductions = 0;
  cliqueReductionSol = 0;
  
  deg2Folds = 0;
  funnelFolds = 0;
  funnelFoldIntersects = 0;
  deskFolds = 0;
}

void Instance::printStats(FILE* file) {
  fprintf(file, "%lu loop reductions added %lu vertices to vc and removed 0 further vertices\n", loopReductions, loopReductions);
  fprintf(file, "%lu deg1 reductions added %lu vertices to vc and removed %lu further vertices\n", deg1Reductions, deg1Reductions, deg1Reductions);
  fprintf(file, "%lu deg2 reductions added %lu vertices to vc and removed %lu further vertices\n", deg2ConnReductions, 2 * deg2ConnReductions, deg2ConnReductions);
  fprintf(file, "%lu deg3 reductions added %lu vertices to vc and removed 0 further vertices\n", deg3Reductions, deg3Reductions);
  fprintf(file, "%lu buss reductions added %lu vertices to vc and removed 0 further vertices\n", bussReductions, bussReductions);  
  fprintf(file, "%lu twin reductions added %lu vertices to vc and removed 0 further vertices\n", twinReductions, twinReductions);  
  fprintf(file, "%lu unconfined reductions added %lu vertices to vc and removed 0 further vertices\n", unconfinedReductions, unconfinedReductions);  
  fprintf(file, "%lu crown reductions added %lu vertices to vc and removed %lu further vertices\n", crownReductions, crownReductionSol, crownReductionRem);  
  fprintf(file, "%lu clique reductions added %lu vertices to vc and removed %lu further vertices\n", cliqueReductions, cliqueReductionSol, cliqueReductions);  

  fprintf(file, "%lu deg2 folds added %lu vertices to vc and removed %lu further vertices\n", deg2Folds, deg2Folds, 2 * deg2Folds);
  fprintf(file, "%lu funnel folds added %lu vertices to vc and removed %lu further vertices\n", funnelFolds, funnelFoldIntersects + funnelFolds, funnelFolds);
  fprintf(file, "%lu desk folds added %lu vertices to vc and removed %lu further vertices\n", deskFolds, 2 * deskFolds, 2 * deskFolds);
}

#endif // NDEBUG
