#include"Functions.hpp"
#include"Good/Relativity.hpp"
#include"Good/Good.hpp"
#include"floor.hpp"
#include"quantum.hpp"

// Opportunity index, maintained incrementally.
// Height lists stay incremental inside change().
// A move's r is recomputed only when this recolor can change it.
// Buckets are rebuilt in indice() order (vertex, then color, skip the
// selected color) so the same rand() shuffle takes the same path.

unsigned long long iter=0;

Movement**index=new Movement*[nVertices*(nColors-1)*(hDegree*4+1)];
Movement***tanq=new Movement**[hDegree*4+1];
Movement***tans=tanq+hDegree*2;
signed mins;

#define Tabu score

// Best conflict count produced by each move. known is false until that
// move has been applied. The tabu ring and the chain are the filters. A filtered move is accepted when its predicted conflict count
// is strictly below best, or strictly below the best score stored for it.
struct MoveBest{
  Score score;
  bool known;
};
MoveBest move_best[nVertices][nColors]{};

Colors color_of(Movement*const m,Vertices const e){
  auto*const row=m-e;
  for(Colors c=0;c<nColors;++c)
    if(movements[c]==row)return c;
  return nColors;
}

void note_move(Movement*const m,Vertices const e){
  Colors const c=color_of(m,e);
  if(c==nColors)return;
  auto& slot=move_best[e][c];
  if(!slot.known||score<slot.score){
    slot.score=score;
    slot.known=true;
  }
}

Delta stored_r[nVertices][nColors];
unsigned char dirty_v[nVertices]={};
Vertices dirty_list[nVertices];
unsigned dirty_n=0;
bool index_ready=false;

unsigned*rev_start=0;
Vertices*rev_adj=0;

void build_reverse(){
  rev_start=new unsigned[nVertices+1]();
  for(Vertices e=0;e<nVertices;++e)
    for(auto const*i=edges+aEdges[e];i<edges+aEdges[e+1];++i)
      ++rev_start[*i+1];
  for(Vertices v=0;v<nVertices;++v)
    rev_start[v+1]+=rev_start[v];
  rev_adj=new Vertices[nEdges];
  auto*cursor=new unsigned[nVertices];
  for(Vertices v=0;v<nVertices;++v)cursor[v]=rev_start[v];
  for(Vertices e=0;e<nVertices;++e)
    for(auto const*i=edges+aEdges[e];i<edges+aEdges[e+1];++i)
      rev_adj[cursor[*i]++]=e;
  delete[]cursor;
}

void mark_one(Vertices const v){
  if(dirty_v[v])return;
  dirty_v[v]=1;
  dirty_list[dirty_n++]=v;
}

// Recoloring x changes x's selected color and every height page of x,
// and the old/new color pages of each out-neighbor (every page, when
// that neighbor wears the old or the new color). r(owner) reads the
// owner's selected color and the height pages of its out-neighbors.
void mark_affected(Vertices const x){
  mark_one(x);
  for(unsigned k=rev_start[x];k<rev_start[x+1];++k)
    mark_one(rev_adj[k]);
  for(auto const*i=edges+aEdges[x];i<edges+aEdges[x+1];++i){
    Vertices const n=*i;
    for(unsigned k=rev_start[n];k<rev_start[n+1];++k)
      mark_one(rev_adj[k]);
  }
}

// Same stacked weights as indice. qrn==0 skips quantum.
// Pointer comparisons are on one neighbor's height ladder.
Delta eval(Vertices const owner,Movement*const m){
  Vertices e=owner;
  auto const*const sv=vertices+e;
  auto const*const ss=sv->selected;
  auto const*const c0=ss-e;
  auto const*const c1=m-e;
  Delta r=0;
  qrn=0;
  loopE{
    setV
    setM(m0,c0)
    setM(m1,c1)
    setH(h0,m0)
    setH(h1,m1)
    setH(h,s)
    if(h1->o==1&&(h1+1)!=h0&&m1==s)r+=1;
    if(m0!=s&&h0->u!=0&&h0<=h)r-=1;
    if(m0==s&&h0->u!=0)r-=2;
    if(m0!=s&&h0->u==0)qr[qrn++]=e;
    if(m0==s&&h0->u==0)r-=4;
  }
  if(qrn)r-=quantum()*3;
  return r;
}

void recompute(Vertices const owner){
  Vertices e=owner;
  auto const*const s=vertices[e].selected;
  for(Colors c=0;c<nColors;++c){
    auto*const m=&movements[c][e];
    if(m!=s)stored_r[e][c]=eval(e,m);
  }
}

void clear_dirty(){
  for(unsigned i=0;i<dirty_n;++i)dirty_v[dirty_list[i]]=0;
  dirty_n=0;
}

#ifdef Audit
#include<cstdlib>
unsigned audit_rounds=0;
void audit(){
  for(Vertices e=0;e<nVertices;++e){
    auto const*const s=vertices[e].selected;
    for(Colors c=0;c<nColors;++c){
      auto*const m=&movements[c][e];
      if(m==s)continue;
      Delta const fresh=eval(e,m);
      if(fresh!=stored_r[e][c]){
        cerr<<"AUDIT e="<<e<<" c="<<(unsigned)c
            <<" stored="<<stored_r[e][c]
            <<" fresh="<<fresh
            <<" iter="<<iter<<endl;
        abort();
      }
    }
  }
  ++audit_rounds;
}
#endif

void inline change(Movement*const m1,Vertices const e){
  ++iter;
  auto*const v=vertices+e;
  auto*const m0=v->selected;
  auto*const c0=m0-e;
  auto*const c1=m1-e;
  auto*const h0=m0->height.l;
  auto*const h1=m1->height.l;
  v->selected=zeromovement,zeromovement=m0;

  ~*m0;

  Change(m0->height,m1->height)

  v->selected=m1,!*m1;

  Delta const dH=h0-h1;
  score-=dH,*v-=dH;
  if(index_ready)mark_affected(e);
}

void inline indice(){
  if(!index_ready){
    for(Vertices e=0;e<nVertices;++e)recompute(e);
    index_ready=true;
  }else{
    for(unsigned i=0;i<dirty_n;++i)recompute(dirty_list[i]);
    clear_dirty();
  }
#ifdef Audit
  if(audit_rounds<500)audit();
#endif
  Delta R=0;
  for(auto i=0u;i<hDegree*4+1;++i)
    tanq[i]=index+nVertices*(nColors-1)*i;
  for(Vertices e=0;e<nVertices;++e){
    auto const*const s=vertices[e].selected;
    for(Colors c=0;c<nColors;++c){
      auto*const m=&movements[c][e];
      if(m!=s){
        Delta const r=stored_r[e][c];
        *(tans[r]++)=m;
        if(r<R)R=r;
      }
    }
  }
  mins=hDegree*2+R;
}

void inline warp(){
  unsigned n=0;
  Vertices tabus[nEdges]={};
  Vertices tabuq[nVertices]={};
  Vertices tabup=-1;
  Score best=score;
A:
  for(auto*i=hIndex.lowest;i<&hIndex.zeropoint;++i){
    auto const*const j=i->z;
    if(*i==j)continue;
    hIndex.lowest=i;
    Movement*const mv=*(*j)->z;
    auto const ev=(*j)->vertex;
    change(mv,ev);
    note_move(mv,ev);
    goto A;
  }
  if(score<best)best=score;
  if(score==0)goto Z;
B:
  indice();
  for(auto i=mins;i<hDegree*4+1;++i){
    auto q=index+nVertices*(nColors-1)*i;
    auto s=tanq[i]-q;
    {
      Movement*p;
      unsigned N;
      for(auto j=0u;j<s;++j)
        N=rand()%s,p=q[j],q[j]=q[N],q[N]=p;
    }
    for(;q<tanq[i];++q){
      auto const m=*q;
      auto const e=m->e;
      bool cont=0;
      for(unsigned j=0;j<Tabu;++j){
        if(tabus[j]==e){
          cont=1;
          break;
        }
      }
      bool chain=tabuq[e]==tabup;
      if(cont||chain){
        auto const*const h0=(vertices+e)->selected->height.l;
        auto const*const h1=m->height.l;
        auto const next=ptrdiff_t(score)-(h0-h1);
        Colors const c=color_of(m,e);
        bool lift=next<ptrdiff_t(best);
        if(!lift&&c<nColors){
          auto const& slot=move_best[e][c];
          lift=slot.known&&next<ptrdiff_t(slot.score);
        }
        if(!lift){
          if(cont)continue;
          tabus[n]=e,n=(n+1)%(Tabu);
          continue;
        }
      }
      tabus[n]=e,n=(n+1)%(Tabu);
      tabuq[e]=tabup;
      tabup=e;
#ifdef PrintPath
      cout<<e<<endl;
#endif
      change(m,e);
      note_move(m,e);
      goto C;
    }
  }
C:
  if(score<best)best=score;
  if(score==0)goto Z;
D:
#ifdef PrintScore
  cout<<score<<','<<best<<','<<iter<<endl;
#endif
  for(auto*i=&hIndex.zeropoint-1;i>=hIndex.lowest;--i){
    for(auto const*j=i->z;*i!=j;j=j->z){
      auto const e=(*j)->vertex;
      auto const m=(*j)->z;
      if(Floor(*m,e))
      {
#ifdef PrintPath
      cout<<e<<endl;
#endif
        change(*m,e);
        note_move(*m,e);
        goto D;
      }
    }
  }
E:
  if(score<best)best=score;
  if(score!=0)goto B;
Z:
  cerr<<iter<<','<<score<<endl;
  return;
}
