#define SPECTRUM_CROSS_LIBRARY #define SPECTRUM_THREE_LIBRARY #define SPECTRUM_ROUTER_LIBRARY #include #include #include #include #include #include #include namespace spectrum { namespace pairing_detail { struct Random { unsigned s; unsigned next() { s ^= s << 13; s ^= s >> 17; return s ^= s << 5; } unsigned index(unsigned n) { return (uint64_t(next()) * n) >> 32; } }; // Pair mirror images of the points (port, input rank). The initial assignment // is bipartite. The subsequent improvement phase may exchange any two edges. inline std::vector initial(const std::vector& a, const std::vector& cost) { const int n = a.size(), h = n / 2; std::vector order(n); std::iota(order.begin(), order.end(), 0); std::stable_sort(order.begin(), order.end(), [&](int i, int j) { return i - a[i] < j - a[j]; }); std::vector u(h+1), v(h+1), owner(h+1), from(h+1), distance(h+1); std::vector used(h+1); for (int i = 1; i <= h; ++i) { owner[0] = i; int col = 0; std::fill(distance.begin(), distance.end(), 1000000000); std::fill(used.begin(), used.end(), 0); do { used[col] = 1; int row = owner[col], shift = 1000000000, next = 0; const int* row_cost = &cost[order[row - 1] * n]; for (int j = 1; j <= h; ++j) if (!used[j]) { int d = row_cost[order[h + j - 1]] - u[row] - v[j]; if (d < distance[j]) { distance[j] = d; from[j] = col; } if (distance[j] < shift) { shift = distance[j]; next = j; } } for (int j = 0; j <= h; ++j) { if (used[j]) { u[owner[j]] += shift; v[j] -= shift; } else distance[j] -= shift; } col = next; } while (owner[col] != 0); do { int prev = from[col]; owner[col] = owner[prev]; col = prev; } while (col != 0); } std::vector partner(n); for (int j = 1; j <= h; ++j) { int x = order[owner[j]-1], y = order[h+j-1]; partner[x] = y; partner[y] = x; } return partner; } struct Matching { const std::vector& a; int n, width; std::vector p, b; std::vector prefix; int inv=0; Matching(const std::vector& ranks, const std::vector& partners) : a(ranks), n(a.size()), width((n+16)&~15), p(partners), b(n), prefix((n+1)*width) { for(int x=0;x y) std::swap(x,y); int X = b[x], Y = b[y]; int low = std::min(X,Y) + 1, high = std::max(X,Y); int change = X < Y ? -1 : 1; const int first=low&~15, last=high&~15; using Bytes=uint8_t __attribute__((vector_size(16),aligned(1),may_alias)); const Bytes lanes={0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15}; const Bytes unit=Bytes{}+static_cast(change); const Bytes left=(lanes>=uint8_t(low&15)) & unit; const Bytes right=(lanes<=uint8_t(high&15)) & unit; auto add_rows=[&](uint8_t* row, int count) { if(first==last) { const Bytes both=left & right; for(int i=0;i(row+first)+=both; } else { for(int i=0;i(row+first)+=left; for(int j=first+16;j(row+j)+=unit; *reinterpret_cast(row+last)+=right; } } }; add_rows(prefix.data()+(x+1)*width,y-x); std::swap(b[x], b[y]); } void exchange(int x, int y, int d) { int u = p[x], v = p[y]; swap_values(x,y); swap_values(u,v); p[x] = v; p[v] = x; p[y] = u; p[u] = y; inv += d; } }; // For each vertical or horizontal grid line, count pairs with ends on // opposite sides. Bits mark the grid lines at capacity and above capacity. // A dual search labels each terminal by its input rank. Capacity is always // measured in the physical grid. All derived AxisCuts in this search use the // same mapping, including repair, triple moves and offspring assessment. struct PhysicalPortOrder { inline static thread_local const int* current=nullptr; const int* previous; explicit PhysicalPortOrder(const int* physical) : previous(current) {current=physical;} ~PhysicalPortOrder() {current=previous;} }; struct AxisCuts { struct Change { uint64_t add, remove; }; int side; std::vector coord; std::array boundary{}; // Plane j stores bit j of 64 + (load - side)/2 on every grid cut. // The cut and the board side have equal parity. std::array levels{}; uint64_t saturated = 0, overloaded = 0; AxisCuts(int n,int axis,const std::vector& p) : side(n/4),coord(n) { for (int i=0; i load{}; for (int i=0; i>j)&1)<side)<=side-1) return 0; int level=0; for(int j=0;j<7;++j) level |= int((levels[j]>>cut)&1)< boundaries{}; BoardCuts(const std::vector& p) : x(p.size(),0,p), y(p.size(),1,p) { for(int i=0;i=1 also refines the exact inversion count of the receiver array. inline std::vector optimize_pairing(const std::vector& input, unsigned seed, int effort, bool feasible) { using namespace pairing_detail; int n = input.size(); if (n == 0) return {}; std::vector a = input; int minimum = *std::min_element(a.begin(), a.end()); for (int& v : a) v -= minimum; std::vector penalty(n), cost(n*n); for (int i=0; i near(n*k), row(n); std::iota(row.begin(),row.end(),0); for (int x=0; x accept{}; for (int d=1; d<128; ++d) accept[d] = uint32_t(4294967295.0*std::exp(-d/temp)); for (int it = 0; it < 12*n; ++it) { int x = rng.index(n); int v = near[x*k + rng.index(k)]; if (s.p[x] == v) continue; int y = s.p[v]; int d = s.delta(x,y); if (d > 0 && (d >= 128 || rng.next() >= accept[d])) continue; if(feasible) { auto cx=cuts.x.change(x,y,s.p[x],v), cy=cuts.y.change(x,y,s.p[x],v); if(!cuts.x.permits(cx) || !cuts.y.permits(cy)) continue; cuts.x.apply(cx); cuts.y.apply(cy); } s.exchange(x,y,d); if (s.inv < best_inv) { best_inv = s.inv; best = s.p; } } } } return best; } inline std::vector choose_partners(const std::vector& a,unsigned seed=1,int effort=1) { return optimize_pairing(a,seed,effort,false); } // Board size is a.size()/4, at most 64. All straight-cut loads are at most N. inline std::vector choose_feasible_partners(const std::vector& a,unsigned seed=1,int effort=1) { return optimize_pairing(a,seed,effort,true); } } // namespace spectrum using namespace std; namespace routing { vector straight(int n) { vector mate(4*n); for (int i=0; i mate, vector& board) { const int m = 4*n; auto cap = straight(n); vector slack(m*m); vector ring(2*m); for (int i=0; i<2*m; ++i) ring[i]=i%m; for (int g=0; g& v, int p, int q) { int u=v[p], w=v[q]; v[p]=w; v[w]=p; v[q]=u; v[u]=q; }; board.assign(n,string(n,'0')); vector reach(m); for (int y=0; y=p ? i-p : i-p+m;}; int a=offset(cap[p]), b=offset(cap[q]); // The two straight rays entering this cell meet exactly here. if (a>=b) return false; auto change=[&](int g,int h,int d) { slack[g*m+h]+=d; slack[h*m+g]+=d; }; exchange(cap,p,q); if (mate[p]!=q) { int u=offset(mate[p]), v=offset(mate[q]); if (ufarthest; --right) { if (s[pos[right]]==0) {farthest=right; break;} } reach[left+1]=farthest; } int u=0,v=0; for (int r=2; r<=low; ++r) { int t=offset(mate[pos[r]]); if (t>high && t>reach[r]) {u=r; v=t; break;} } if (!u) return false; for (int i=u; i& board, const vector& p) { int n=board.size(),m=4*n; constexpr int dy[]={-1,0,1,0}, dx[]={0,1,0,-1}; for (int i=0;i=0 && r=0 && c=n ? n+r : r>=n ? 3*n-1-c : 4*n-1-r; if (p[i]!=j) return false; } return true; } } // namespace routing #ifndef SPECTRUM_ROUTER_LIBRARY int main() { ios::sync_with_stdio(false); cin.tie(nullptr); int n; if (!(cin>>n)) return 0; vector a(4*n); for (int& v:a) {cin>>v;--v;} vector board; auto target=spectrum::choose_feasible_partners(a,1,8); if (!routing::draw(n,target,board) || !routing::realizes(board,target)) board.assign(n,string(n,'0')); for (auto& row:board) cout<& a; int m, width; Matching s; BoardCuts cuts; Random rng; vector raw; vector> near; CycleSearch(const vector& ranks,const vector& start,unsigned seed) : a(ranks),m(a.size()),width(min(18,m-1)),s(a,start),cuts(start),rng{seed}, raw(m*m),near(m) { for(int i=0;i before(m); for(int i=0;ib[k])+(oldj>oldk)-(oldj>b[k])-(b[j]>oldk); else linear+=(b[j]s.p[x] || x>s.p[y]) continue; int d=s.delta(x,y); if(d>=bd) continue; if(!cuts.x.permits(cuts.x.change(x,y,s.p[x],s.p[y])) || !cuts.y.permits(cuts.y.change(x,y,s.p[x],s.p[y]))) continue; bd=d;bx=x;by=y; } for(int x=0;x=bd)continue; int d=delta(x,y,z,linear); if(d>=bd || !permits(x,y,z))continue; bd=d;bx=x;by=y;bz=z; } } if(bd==0)return false; if(bz<0)elementary(bx,by); else cycle(bx,by,bz); return true; } void perturb(int steps,int max_cost) { for(int trials=0;steps>0 && trials<3000;++trials) { int x=rng.index(m),v=near[x][rng.index(width)],y=s.p[v]; if(x==y || s.p[x]==y)continue; int d=s.delta(x,y); if(d>max_cost || (d>0 && rng.index(d/3+1)>0))continue; if(!cuts.x.permits(cuts.x.change(x,y,s.p[x],v)) || !cuts.y.permits(cuts.y.change(x,y,s.p[x],v))) continue; elementary(x,y);--steps; } } }; vector refine(const vector& a,const vector& initial,Time::time_point deadline,unsigned seed) { CycleSearch engine(a,initial,seed); int best_inv=engine.s.inv; auto best=initial; int stalls=0; while(Time::now()best_inv || ++stalls%4==0) { Matching reset(a,best); engine.s.p.swap(reset.p);engine.s.b.swap(reset.b); engine.s.prefix.swap(reset.prefix);engine.s.inv=best_inv; engine.cuts=BoardCuts(best); } int strength=5+engine.rng.index(12)+min(16,stalls/2); engine.perturb(strength,12+strength); } } return best; } } #ifndef SPECTRUM_THREE_LIBRARY int main() { ios::sync_with_stdio(false);cin.tie(nullptr); int n; if(!(cin>>n))return 0; auto deadline=chrono::steady_clock::now()+chrono::milliseconds(1460); vector a(4*n);for(int& v:a) {cin>>v;--v;} auto first=spectrum::choose_feasible_partners(a,1,8); auto target=triple_search::refine(a,first,deadline,1181); vector board; if(!routing::draw(n,target,board) || !routing::realizes(board,target)) { if(!routing::draw(n,first,board) || !routing::realizes(board,first)) board.assign(n,string(n,'0')); } for(auto& row:board)cout< #include namespace spectrum { namespace advanced_detail { using pairing_detail::AxisCuts; using pairing_detail::BoardCuts; using pairing_detail::Matching; using pairing_detail::Random; // Remove up to eight pairs. Each replacement edge has an exact unary cost // against the fixed ports. Two replacement edges additionally interact through // four inversion indicators. A subset matching DP on unary costs bounds DFS. struct Cluster { static constexpr int limit=16; int size, full, best_cost=0, visits=0; int node[limit], rank[limit], original[limit], choice[limit], result[limit]; int unary[limit][limit], order[limit][limit], memo[1<=0) return ans; int i=__builtin_ctz(mask); int remain=mask^(1<::max()/2; for(int bits=remain; bits; bits&=bits-1) { int j=__builtin_ctz(bits); ans=std::min(ans,unary[i][j]+bound(remain^(1<side) return false; } } return true; } void explore(int mask,int partial) { if(partial+bound(mask)>=best_cost || ++visits>1700) return; if(mask==0) { if(feasible()) { best_cost=partial; std::copy_n(choice,size,result); } return; } int i=__builtin_ctz(mask), remain=mask^(1<=best_cost) continue; for(int k=0; k1700) break; } } bool refine(Matching& s,BoardCuts& cuts,const std::vector& picked) { size=picked.size(); full=(1< nearest(const std::vector& a,int count,bool reflected) { int n=a.size(); std::vector table(n*count),ord(n),cost(n); std::iota(ord.begin(),ord.end(),0); for(int i=0;i& neighbors,int count, int& best_inv,std::vector& best,int round) { constexpr int stages=20; const int initial_t=round%5==0?19:round%3==0?10:6; int bad=total_excess(cuts); for(int stage=0;stage accept{}; for(int i=1;i<160;++i) accept[i]=uint32_t(4294967295.0*std::exp(-i/temp)); for(int iter=0;iter<12*s.n;++iter) { int x=rng.index(s.n),v=neighbors[x*count+rng.index(count)]; if(s.p[x]==v) continue; int y=s.p[v],u=s.p[x]; auto cx=cuts.x.change(x,y,u,v),cy=cuts.y.change(x,y,u,v); int gain=cuts.x.overload_gain(cx)+cuts.y.overload_gain(cy); if(!soft && gain<0) continue; int d=s.delta(x,y); int objective=d-price*gain; if(objective>0 && (objective>=160 || rng.next()>=accept[objective])) continue; s.exchange(x,y,d); cuts.x.apply(cx); cuts.y.apply(cy); bad-=gain; if(!bad && s.inv cluster_nodes(const Matching& s,Random& rng,const std::vector& nearby,int count,int pairs) { int anchor=rng.index(s.n); for(int i=0;i<2;++i) { int t=rng.index(s.n); if(std::abs(t-s.b[t])>std::abs(anchor-s.b[anchor])) anchor=t; } std::vector nodes{anchor,s.p[anchor]},pool; pool.reserve(count); for(int t=0;t choose_advanced_partners(const std::vector& input,unsigned seed=1,int milliseconds=1450) { using namespace advanced_detail; using Clock=std::chrono::steady_clock; auto end=Clock::now()+std::chrono::milliseconds(milliseconds); std::vector a=input; int low=*std::min_element(a.begin(),a.end()); for(int& v:a) v-=low; auto best=choose_feasible_partners(a,seed,milliseconds>=15?2:0); if(a.size()<8 || milliseconds<15) return best; Random rng{seed?seed:1}; int count=std::min(40,int(a.size())-1); auto proposals=nearest(a,count,true), nearby=nearest(a,count,false); Matching initial(a,best); int best_inv=initial.inv; std::vector current=best; Cluster cluster; for(int round=0;Clock::now()0) anneal(s,cuts,rng,proposals,count,best_inv,best,round); if(s.inv=end) break; int pairs=std::min(int(a.size()/2),int(5+rng.index(4))); auto nodes=cluster_nodes(s,rng,nearby,count,pairs); if(cluster.refine(s,cuts,nodes) && s.inv p; }; struct Recombination { // Different perfect matchings partition their differing vertices into // alternating cycles, each of which can independently select either parent. static constexpr int MaxCycles = 64, MaxCuts = 126; const Individual &first, &second; const vector& a; int n, count=0, cutCount=0, best, work=0; uint64_t solution=0; vector cycle; int unary[MaxCycles]{}, interaction[MaxCycles][MaxCycles]{}; int linear[MaxCycles], futureDiscount[MaxCycles]{}, order[MaxCycles]; int loads[MaxCuts], changes[MaxCycles][MaxCuts]{}, minTail[MaxCycles+1][MaxCuts]{}; Deadline deadline; Recombination(const vector& ranks, const Individual& left, const Individual& right, Deadline end) : first(left),second(right),a(ranks),n(a.size()),best(left.inv),cycle(n,-1),deadline(end) { for(int i=0;i old(n),alt(n); for(int i=0;iold[j], f11=alt[i]>alt[j]; if(u==v) unary[u]+=f11-f00; else { int f10=alt[i]>old[j], f01=old[i]>alt[j]; if(u>=0) unary[u]+=f10-f00; if(v>=0) unary[v]+=f01-f00; if(u>=0 && v>=0) { int mixed=f11-f10-f01+f00; interaction[u][v]+=mixed; interaction[v][u]+=mixed; } } } } void capacity() { BoardCuts base(first.p); for(const auto* axis : {&base.x,&base.y}) { int diff[MaxCycles][65]{}; for(int i=0;i=0) { auto accumulate=[&](int j,int sign) { if(i>=j) return; int z=axis->coord[i], w=axis->coord[j]; diff[cycle[i]][min(z,w)]+=sign; diff[cycle[i]][max(z,w)]-=sign; }; accumulate(first.p[i],-1);accumulate(second.p[i],1); } for(int k=0;kside-1;++k) { int worst=axis->load_at(k); for(int u=0;uside) continue; // Store slack-relative load so that the compatible choices // have a nonpositive total for every retained constraint. loads[cutCount]=axis->load_at(k)-axis->side; for(int u=0;u strength(count); for(int u=0;ustrength[y];}); for(int i=count-1;i>=0;--i) { int u=order[i]; for(int j=i+1;j14000) return; if(!(work&255) && Clock::now()>=deadline) {work=15000;return;} int lower=inv; for(int j=depth;j=best) return; for(int k=0;k0) return; if(depth==count) {best=inv;solution=mask;return;} int u=order[depth]; auto select=[&]() { for(int j=depth+1;j=0 && ((solution>>cycle[i])&1)) result.p[i]=second.p[i]; return result; } }; int distance(const Individual& a,const Individual& b) { return inner_product(a.p.begin(),a.p.end(),b.p.begin(),0,plus(),not_equal_to()); } void admit(vector& pool, Individual child) { int close=-1, minDistance=INT_MAX; for(int i=0;i<(int)pool.size();++i) { int d=distance(pool[i],child); if(d12) { int remove=-1, largest=INT_MIN; int leader=min_element(pool.begin(),pool.end(),[](const auto& a,const auto& b){ return a.invlargest) {largest=rating;remove=i;} } pool.erase(pool.begin()+remove); } } sort(pool.begin(),pool.end(),[](const auto& a,const auto& b){return a.inv& a,vector p) { int inv=Matching(a,p).inv; return {inv,move(p)}; } vector optimize(const vector& a,Deadline start) { Random rng{341579}; int nearCount=min(40,int(a.size())-1); auto neighbors=spectrum::advanced_detail::nearest(a,nearCount,true); auto initial=assessed(a,spectrum::choose_feasible_partners(a,1,5)); auto alternate=assessed(a,spectrum::choose_advanced_partners(a,rng.next(),135)); vector pool{initial}; admit(pool,move(alternate)); Deadline evolutionEnd=start+chrono::milliseconds(1510); Deadline searchEnd=start+chrono::milliseconds(1815); for(int generation=0;Clock::now() visited=anchor.p; int heat=generation%4==0 ? 5 : generation%4==1 ? 3 : 2; spectrum::advanced_detail::anneal(s,cuts,rng,neighbors,nearCount,bestInv,visited,heat); // Preserve a new basin through local descent, even when its first // annealing pass did not improve the parent. Individual child=assessed(a,generation%3==0 ? move(visited) : move(s.p)); Deadline polish=min(evolutionEnd,Clock::now()+chrono::milliseconds(generation%3==0?42:24)); if(Clock::now() mates(pool.size());iota(mates.begin(),mates.end(),0); for(int j=1;j<(int)mates.size();++j) swap(mates[j],mates[j+rng.index(mates.size()-j)]); for(int j:mates) { if(Clock::now()>=evolutionEnd) break; auto mix=Recombination(a,pooled,pool[j],evolutionEnd).run(); if(mix.inv>n)) return 0; vector a(4*n); for(int& v:a) {cin>>v;--v;} auto target=breeding::optimize(a,start); vector board; if(!routing::draw(n,target,board) || !routing::realizes(board,target)) board.assign(n,string(n,'0')); for(const auto& row:board) cout< assignment(const std::vector& c,int n) { std::vector owner(n+1),prev(n+1),u(n+1),v(n+1),d(n+1),ans(n); std::vector used(n+1); for(int i=1;i<=n;++i) { owner[0]=i; std::fill(d.begin(),d.end(),1000000000); std::fill(used.begin(),used.end(),0); int k=0; do { used[k]=1; int shift=1000000000, next=0, row=owner[k]; auto cost=&c[(row-1)*n]; for(int j=1;j<=n;++j) if(!used[j]) { int s=cost[j-1]-u[row]-v[j]; if(s best; // Proposed partners collectively form alternating cycles with the current // matching. Each cycle can be committed independently after checking all // affected score terms and both grid-coordinate capacities. void step(Matching& s, BoardCuts& cuts, Random& rng,int phase) { int keep=phase%4==0?100:40+rng.index(61); std::vector l,r; for(int i=0;ib-s.a[b])std::swap(a,b); if(rng.index(100)<(phase%3==2?30u:6u))std::swap(a,b); l.push_back(a);r.push_back(b); } int m=l.size(); if(m<2) return; std::vector where(s.n),c(m*m); for(int i=0;iy : y>x;}; int price[2][65]{}; int shadow=phase%4==0?0:1+rng.index(16); for(int k=0;k seen(m); std::vector cycle; for(int start=0;start0;--j)exchange(s,cuts,cycle[j-1],cycle[j]); } } } }; } // namespace global_detail inline std::vector choose_global_partners(const std::vector& input,unsigned seed=1,int milliseconds=1450) { using namespace global_detail; using Clock=std::chrono::steady_clock; auto end=Clock::now()+std::chrono::milliseconds(milliseconds); std::vectora=input; int low=*std::min_element(a.begin(),a.end()), n=a.size(); for(int& p:a)p-=low; bool identity=true,exact=true; for(int i=0;i p(n); for(int i=0;i=15?2:0); if(n<8 || milliseconds<15)return p; Random rng{seed?seed:1}; int count=std::min(40,n-1); auto nearby=nearest(a,count,false),proposals=nearest(a,count,true); Matching init(a,p);CycleSearch search{init.inv,p}; Cluster cluster; for(int round=0;Clock::now()0)anneal(s,cuts,rng,proposals,count,search.best_inv,search.best,round); if(s.inv=end) return false; if(i>=s.p[i])continue; for(int j=i+1;j board; vector partners; Incumbent(int side,const vector& a) : n(side),inv(Matching(a,routing::straight(n)).inv),board(n,string(n,'0')),partners(routing::straight(n)) {} void consider(const vector& a,const vector& p) { int score=Matching(a,p).inv; if(score>=inv)return; vector candidate; if(routing::draw(n,p,candidate) && routing::realizes(candidate,p)) { inv=score;board=move(candidate);partners=p; } } }; // Hard and soft annealing share the best feasible target. Regional rounds // reheat only pairs near one part of the current permutation. #if defined(__GNUC__) && defined(__x86_64__) __attribute__((target_clones("popcnt","default"))) #endif void anneal(Matching& s,BoardCuts& cuts,Random& rng,const vector& nearby, const vector& proposals,int width,int round,bool regional, CycleSearch& best,Deadline end) { int bad=spectrum::advanced_detail::total_excess(cuts); vector focus; if(regional) { int x=rng.index(s.n); for(int j=0;j<4;++j) { int z=rng.index(s.n); if(abs(z-s.b[z])>abs(x-s.b[x]))x=z; } focus={x,s.p[x]}; for(int j=0;j accept{}; for(int d=1;d<160;++d)accept[d]=uint32_t(4294967295.*exp(-d/temp)); for(int t=0;t<(regional?9:12)*s.n;++t) { int x=regional?focus[rng.index(focus.size())]:int(rng.index(s.n)); int v=proposals[x*width+rng.index(width)]; if(v==s.p[x])continue; int y=s.p[v],u=s.p[x]; auto change=cuts.change(x,y,u,v); int gain=cuts.gain(change); if(!soft && gain<0)continue; int d=s.delta(x,y,u,v),objective=d-price*gain; if(objective>0 && (objective>=160 || rng.next()>=accept[objective]))continue; cuts.apply(change);s.exchange(x,y,d);bad-=gain; if(!bad && s.inv label,physical,ranks; SearchFrame(const vector& a,bool transpose,bool reverse) : label(a.size()),physical(a.size()),ranks(a.size()) { int n=a.size(); for(int x=0;x encode(const vector& p) const { vector q(p.size()); for(int x=0;x<(int)p.size();++x)q[label[x]]=label[p[x]]; return q; } vector decode(const vector& q) const { vector p(q.size()); for(int u=0;u<(int)q.size();++u)p[physical[u]]=physical[q[u]]; return p; } }; // Small symmetric noise on the reflected-point assignment changes which // near-tied pairs seed the two later families. All subsequent scoring is exact. vector initial_family(const vector& a,unsigned seed,bool perturb) { if(!perturb)return spectrum::choose_partners(a,1,0); int n=a.size(); vector cost(n*n), penalty(n); Random rng{seed}; for(int i=0;i void run_phase(const vector& a,const vector& fallback,Deadline start, Deadline search_end,unsigned seed,const Individual* warm,bool perturb, Consider&& consider) { int n=a.size(); auto p=initial_family(a,seed,perturb); Matching init(a,p); BoardCuts init_cuts(p); if(repair(init,init_cuts,min(search_end,start+chrono::milliseconds(65))))p=init.p; else p=fallback; CycleSearch best{Matching(a,p).inv,p}; consider(best.best_inv,p); Random rng{seed}; int width=min(40,n-1); auto nearby=spectrum::advanced_detail::nearest(a,width,false); auto proposals=spectrum::advanced_detail::nearest(a,width,true); vector pool{{best.best_inv,p}}; Cluster cluster; auto checkpoint=start+chrono::milliseconds(180); for(int round=0;Clock::now()invinv;best.best=warm->p; } } bool breed=round>=6 && round%6==4; bool regional=round>=6 && round%6==3; const auto& parent=breed && pool.size()>1 ? pool[1+rng.index(pool.size()-1)].p : round%3==0?p:best.best; Matching s(a,parent); BoardCuts cuts(s.p); anneal(s,cuts,rng,nearby,proposals,width,round,regional,best,search_end); if(cuts.x.overloaded || cuts.y.overloaded) { if(!repair(s,cuts,min(search_end,Clock::now()+chrono::milliseconds(4))))continue; } if(s.inv1 && Clock::now()inv)) child=move(mix); } if(child.inv=checkpoint) { consider(best.best_inv,best.best); checkpoint=Clock::now()+chrono::milliseconds(380); } } consider(best.best_inv,best.best); } vector solve(const vector& a,int side,Deadline start) { int n=a.size(); auto limit=start+chrono::milliseconds(1820); auto search_end=limit-chrono::milliseconds(12); Incumbent incumbent(side,a); vector adjacent(n); for(int i=0;i0;++phase) { auto phase_start=Clock::now(); auto phase_end=min(search_end,start+chrono::milliseconds(finish_ms[phase])); if(phase_start>=phase_end)continue; SearchFrame frame(a,phase&1,phase&2); Individual carry{incumbent.inv,frame.encode(incumbent.partners)}; auto fallback=frame.encode(adjacent); spectrum::pairing_detail::PhysicalPortOrder order(frame.physical.data()); auto consider=[&](int inv,const vector& p) { if(inv=2,consider); } return incumbent.board; } } // namespace portfolio int main() { ios::sync_with_stdio(false);cin.tie(nullptr); const auto start=portfolio::Clock::now(); int n; if(!(cin>>n))return 0; vector a(4*n); for(int& v:a){cin>>v;--v;} auto board=portfolio::solve(a,n,start); for(const auto& row:board)cout<