#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

  // One record per movement, parallel to movements[color][vertex].
  // The first time a movement is taken it stays tabu for 1 iteration,
  // the second time for 2, then 3, and so on. Each take adds 1.
  // move_iter stores the iteration of the last take and move_times how
  // many times it has been taken. A repeat is allowed when
  // iter >= move_iter + move_times. A movement never taken has times 0
  // and is free. iter starts at 0. Aspiration still admits a tabu move
  // when score+dH is strictly below best.
  static unsigned const kTabuStep=1;
  unsigned long long move_iter[nColors*nVertices]={};
  unsigned move_times[nColors*nVertices]={};
  Score best=~Score(0);
  // Counts iterations. It does not stop the search.
  unsigned long long iter=0;

  unsigned move_index(Movement*const m)const{
    unsigned const v=m->vertex;
    unsigned const c=(unsigned)((m-v-movements[0])/nVertices);
    return c*(unsigned)nVertices+v;
  }

  bool inline forbidden(Movement*const m)const{
    unsigned const i=move_index(m);
    unsigned const times=move_times[i];
    if(!times)return false;
    return iter<move_iter[i]+kTabuStep*(unsigned long long)times;
  }

  // The tabu belongs to the movement, not to the vertex. Another color
  // of the same vertex is a different movement.
  bool inline vertex_held(unsigned)const{
    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);
    if(zerocolor.score<best)best=zerocolor.score;
    ++iter;
    unsigned const i=c*(unsigned)nVertices+v;
    ++move_times[i];
    move_iter[i]=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;
    for(unsigned i=0;i<nColors*(unsigned)nVertices;++i){
      move_iter[i]=0;
      move_times[i]=0;
    }
    iter=0;
    opp_build();
  }

#include"Opportunity.hpp"
};
