#include"Functions.hpp"
#include"Instructions.hpp"
#include"Relativity.hpp"
#include<cstdlib>
#include<cstring>

// Horizon of the opportunity chain. 1 is the adjacency only.
// 2 is the first chain in which the triangle mark removes a vertex.
// The 2017 dH index stays exact either way.
#ifndef Horizon
#define Horizon 2
#endif

struct Indexed{
  Index negatives[hDegree];
  Index zeropoint;
  Index positives[hDegree];

  Heights heights[nHeights];
  Potentials potentials[nHeights];
  Vertex vertices[nVertices];

  ZeroColor zerocolor;

  Movement movements[nColors][nVertices];

  inline Indexed(){
    for(Vertices v=0;v<nVertices;++v){
      auto const D=vEdges[v];
      auto const E=aEdges[v]+v;
      auto*const H=heights+E;
      auto*const P=potentials+E;
      auto*const V=vertices+v;
      (*V)(&zerocolor);
      for(Edges d=0;d<=D;++d)
        P[d](&zeropoint+d,V);
      for(auto&c:movements){
        c[v](H,P);
//TODO
        c[v].vertex=v;
      }
    }
    opp_init();
  }
  //TODO NP!=P
  struct LinkableVertex;
  struct LinkableVertices:List<LinkableVertex>{};
  struct LinkableVertex:Element<LinkableVertex,LinkableVertices,void,0>{
    Vertices v;
  };

  struct Branch;
  struct LinkableBranches:List<Branch>{};

  struct Branch:Element<Branch,LinkableBranches,void,0>{
    LinkableVertices p;
    LinkableVertices e;
    LinkableBranches b;

    //destructor muere todas

    unsigned long long inline result(Indexed*const in){
      unsigned long long sum=0;
      loopL((&e)){
        auto*const a=new Branch();
        (*a)(&b),~(*a);
        auto*const v=new LinkableVertex();
        auto const e=i->v;
        (*v)(&a->p),~(*v),v->v=e;
        loopL((&p)){
          auto*const v=new LinkableVertex();
          auto const p=i->v;
          (*v)(&a->p),~(*v),v->v=p;
          loopE{
            auto const e=edges[i];
            if(e!=p){
              auto*const n=new LinkableVertex();
              (*n)(&a->e),~(*n),n->v=e;
              in->movements[0][e].height.l-(in->heights+aEdges[e]+e);
            }
          }
        }
      }
    }
  };

  Branch branches[nVertices];
  Vertices nBranches;
  //TODO NP!=P END

  // Last 20 movements taken by solve(). A movement is one vertex-color.
  // A move that raises the conflict count also holds its vertex for those
  // twenty steps. The reverse is otherwise the next improving move, and the
  // search returns to the same score. A flat move does not hold the vertex.
  static unsigned const kTabu=20;
  Movement*tabu[kTabu]={};
  unsigned tabu_vertex[kTabu]={};
  bool tabu_climb[kTabu]={};
  unsigned tabun=0;
  Score best=~Score(0);
  // Counts iterations. It does not stop the search.
  unsigned long long iter=0;

  bool inline forbidden(Movement*const m)const{
    unsigned const n=tabun<kTabu?tabun:kTabu;
    for(unsigned i=0;i<n;++i)
      if(tabu[i]==m)return true;
    return false;
  }

  bool inline vertex_held(unsigned v)const{
    unsigned const n=tabun<kTabu?tabun:kTabu;
    for(unsigned i=0;i<n;++i)
      if(tabu_climb[i]&&tabu_vertex[i]==v)return true;
    return false;
  }

  void inline take(Movement*const m){
#ifdef PrintPath
    cout<<m->vertex<<endl;
#endif
    unsigned const v=m->vertex;
    unsigned const c=(unsigned)((m-v-movements[0])/nVertices);
    int const dh=bucket_of(v,c);
    change(m);
    unsigned const slot=tabun%kTabu;
    tabu[slot]=m;
    tabu_vertex[slot]=v;
    // Only a climb is held. Its reverse lowers the count, so without the
    // hold the next step undoes it. Aspiration can still take the vertex
    // when score+dH is strictly below best.
    tabu_climb[slot]=dh>0;
    ++tabun;
    if(zerocolor.score<best)best=zerocolor.score;
    ++iter;
#ifdef PrintScore
    cout<<zerocolor.score<<','<<best<<','<<iter<<endl;
#endif
  }

  Colors inline count(){
    auto const*m=movements[0];
    for(Vertices e=0;e<nVertices;++e)
      if(vertices[e].selected-e>m)
        m=vertices[e].selected;
    return(m-movements[0])/nVertices;
  }

  inline Movement*algo(){
    auto*m=movements[0];
    for(Vertices e=0;e<nVertices;++e){
      auto*const a=vertices[e].selected-e;
      if(a>m)
        m=a;
    }
    return m;
  }

  void inline shrink(){
    auto*c=algo();
    auto*X=c+nVertices;
    for(auto*C=X;C<movements[zerocolor.colors];++C)
      !*C;
    for(Vertices e=0;e<nVertices;++e){
      auto const*const v=vertices+e;
      if(v->selected==c+e){
        auto const*p=potentials+aEdges[e]+e;
        while(*p==p->z)++p;
        change(*p->z);
      }
    }
    for(;c<X;++c)
      !*c;
    zerocolor.colors=count();
  }

  void inline change(Movement*const m1){
    auto const e=m1->vertex;
    auto*const v=vertices+e;
    auto*const m0=v->selected;
    setC(c0,m0)
    setC(c1,m1)
    setH(h0,m0)
    setH(h1,m1)

    ~*m0,zerocolor(m0),(*v)(&zerocolor);
    //TODO Guardar potential.l, luego si no hay dZ revisar si está activo y haceR?
    //*(m0->potential.l->position);
    *(m1->potential.l->position);

    Change(*m0,*m1)

    Delta const dH=h1-h0;
    zerocolor.score+=dH;

    !*m1,v->selected=m1;

    if(dH)movZ(-dH)
    //else{
      //*(m0->potential.l->position);
      //*(m1->potential.l->position);
    //}
    // dH buckets above are already the new coloring. Opportunity reads them
    // and rewrites only the ball this vertex can reach.
    if(opp_ready)opp_step(e);
  }

  void inline start(){
    for(Vertices e=0;e<nVertices;++e){
#ifdef Solution
      auto*const c1=movements[Solution[e]];
#else
      auto*const c1=movements[0];
#endif
      setM(m1,c1)
      setH(h1,m1)

      Start(*m1)

      auto const*const h=heights+aEdges[e]+e;
      Delta const dH=h1-h;
      zerocolor.score+=dH;

      auto*const v=vertices+e;
      !*m1,v->selected=m1;

      if(dH)movZ(-dH)
    }
    best=zerocolor.score;
    tabun=0;
    opp_build();
  }

#include"Opportunity.hpp"
};
