結果

問題 No.5026 Spectrum Router
コンテスト
ユーザー Keroru
提出日時 2026-11-23 23:03:13
言語 C++23
(gcc 15.3.0 + boost 1.92.0 + ACL)
コンパイル:
g++-15 -O2 -fplugin=/usr/lib/yukicoder/noavx512-gcc15.so -lm -std=c++23 -Wuninitialized -DONLINE_JUDGE -o a.out _filename_
実行:
./a.out
結果
AC  
実行時間 1,798 ms / 2,000 ms
+ 447µs
コード長 60,906 bytes
記録
記録タグの例:
初AC ショートコード 純ショートコード 純主流ショートコード 最速実行時間
コンパイル時間 6,390 ms
コンパイル使用メモリ 407,524 KB
実行使用メモリ 9,868 KB
スコア 1,560,237
最終ジャッジ日時 2026-11-23 23:16:21
合計ジャッジ時間 101,964 ms
ジャッジサーバーID
(参考情報)
judge6_0 / judge1_0
純コード判定しない問題か言語
このコードへのチャレンジ
(要ログイン)
ファイルパターン 結果
other AC * 50
権限があれば一括ダウンロードができます

ソースコード

diff #
raw source code

#define SPECTRUM_CROSS_LIBRARY
#define SPECTRUM_THREE_LIBRARY
#define SPECTRUM_ROUTER_LIBRARY
#include <bits/stdc++.h>
#include <algorithm>
#include <array>
#include <cmath>
#include <cstdint>
#include <numeric>
#include <vector>

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<int> initial(const std::vector<int>& a, const std::vector<int>& cost) {
    const int n = a.size(), h = n / 2;
    std::vector<int> 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<int> u(h+1), v(h+1), owner(h+1), from(h+1), distance(h+1);
    std::vector<char> 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<int> 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<int>& a;
    int n, width;
    std::vector<int> p, b;
    std::vector<uint8_t> prefix;
    int inv=0;
    Matching(const std::vector<int>& ranks, const std::vector<int>& partners)
        : a(ranks), n(a.size()), width((n+16)&~15), p(partners), b(n), prefix((n+1)*width) {
        for(int x=0;x<n;++x) {
            b[x]=a[p[x]];
            const uint8_t* cur=prefix.data()+x*width;
            uint8_t* next=prefix.data()+(x+1)*width;
            for(int y=0;y<=n;++y) next[y]=cur[y]+(b[x]<y);
            inv+=x-cur[b[x]];
        }
    }
    // The only prefix count that cannot fit in one byte is (256,256).
    int less(int r,int t) const {
        if(t==256 && r==256) return 256;
        return prefix[r*width+t];
    }
    // For a swap at i,j with ranks I,J, this oriented half-open rectangle
    // contains the lower left endpoint precisely when the pair is concordant.
    // Its signed count C therefore gives the inversion difference 2*C-1.
    int rectangle(int i,int j,int I,int J) const {
        const uint8_t* pi=prefix.data()+i*width;
        const uint8_t* pj=prefix.data()+j*width;
        return pj[J]-pj[I]-pi[J]+pi[I];
    }
    int delta(int x,int y) const { return delta(x,y,p[x],p[y]); }
    int delta(int x,int y,int u,int v) const {
        const int X=b[x],Y=b[y],U=b[u],V=b[v];
        // The first swap changes two points in the second rectangle.
        int rows=(x<v)-(x<u)-(y<v)+(y<u);
        int cols=(Y<V)-(Y<U)-(X<V)+(X<U);
        return 2*(rectangle(x,y,X,Y)+rectangle(u,v,U,V)+rows*cols-1);
    }

    void swap_values(int x, int y) {
        if (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<uint8_t>(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<count;++i,row+=width)
                    *reinterpret_cast<Bytes*>(row+first)+=both;
            } else {
                for(int i=0;i<count;++i,row+=width) {
                    *reinterpret_cast<Bytes*>(row+first)+=left;
                    for(int j=first+16;j<last;j+=16) *reinterpret_cast<Bytes*>(row+j)+=unit;
                    *reinterpret_cast<Bytes*>(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<int> coord;
    std::array<uint64_t,256> 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<uint64_t,7> levels{};
    uint64_t saturated = 0, overloaded = 0;

    AxisCuts(int n,int axis,const std::vector<int>& p) : side(n/4),coord(n) {
        for (int i=0; i<n; ++i) {
            int port=PhysicalPortOrder::current ? PhysicalPortOrder::current[i] : i;
            int s=port/side, k=port%side;
            if (axis==0) coord[i] = s==0 ? k : s==1 ? side-1 : s==2 ? side-1-k : 0;
            else coord[i] = s==0 ? 0 : s==1 ? k : s==2 ? side-1 : side-1-k;
        }
        std::array<int,64> load{};
        for (int i=0; i<n; ++i) boundary[i]=(uint64_t(1)<<coord[i])-1;
        for (int i=0; i<n; ++i) if(i<p[i]) {
            int lo=std::min(coord[i],coord[p[i]]), hi=std::max(coord[i],coord[p[i]]);
            for (int k=lo; k<hi; ++k) ++load[k];
        }
        for(int k=0; k<side-1; ++k) {
            int level=64+(load[k]-side)/2;
            for(int j=0;j<7;++j) levels[j] |= uint64_t((level>>j)&1)<<k;
            overloaded |= uint64_t(load[k]>side)<<k;
        }
        saturated=levels[6];
    }
    int load_at(int cut) const {
        if(cut>=side-1) return 0;
        int level=0;
        for(int j=0;j<7;++j) level |= int((levels[j]>>cut)&1)<<j;
        return side+2*(level-64);
    }
    // A cut changes iff x,y and u,v each straddle it. When x,u lie on
    // the same side, both new pairs cross; otherwise both old pairs cross.
    Change change(int x,int y,int u,int v) const {
        uint64_t a=boundary[x], b=boundary[y], c=boundary[u], d=boundary[v];
        uint64_t affected=(a^b)&(c^d), before=a^c;
        return {affected & ~before,affected & before};
    }
    void apply(Change c) {
        if(!(c.add|c.remove)) return;
        uint64_t carry=c.add|c.remove;
        for(int j=0;j<6;++j) {
            uint64_t old=levels[j];
            levels[j]=old^carry;
            carry &= old^c.remove;
        }
        levels[6]^=carry;
        if(c.add) overloaded |= saturated & c.add;
        else {
            uint64_t nonzero=levels[0]|levels[1]|levels[2]|levels[3]|levels[4]|levels[5];
            overloaded=(overloaded & ~c.remove) | (c.remove & levels[6] & nonzero);
        }
        saturated=levels[6];
    }
    int overload_gain(Change c) const {
        uint64_t up=c.add&saturated, down=c.remove&overloaded;
        if(!(up|down)) return 0;
        return up ? -__builtin_popcountll(up) : __builtin_popcountll(down);
    }
    bool permits(Change c) const { return !(c.add & saturated); }
};

struct BoardCuts {
    AxisCuts x,y;
    using Plane=uint64_t __attribute__((vector_size(16)));
    struct Switch { Plane add,remove; };
    std::array<Plane,256> boundaries{};
    BoardCuts(const std::vector<int>& p) : x(p.size(),0,p), y(p.size(),1,p) {
        for(int i=0;i<int(p.size());++i) boundaries[i]=Plane{x.boundary[i],y.boundary[i]};
    }
    Switch change(int i,int j,int u,int v) const {
        Plane a=boundaries[i],b=boundaries[j],c=boundaries[u],d=boundaries[v];
        Plane affected=(a^b)&(c^d), before=a^c;
        return {affected & ~before, affected & before};
    }
    int gain(Switch step) const {
        Plane up=step.add & Plane{x.saturated,y.saturated};
        Plane down=step.remove & Plane{x.overloaded,y.overloaded};
        Plane moved=up | down;
        int gx=__builtin_popcountll(moved[0]), gy=__builtin_popcountll(moved[1]);
        return (up[0]?-gx:gx) + (up[1]?-gy:gy);
    }
    void apply(Switch step) {
        x.apply({step.add[0],step.remove[0]});
        y.apply({step.add[1],step.remove[1]});
    }
    // When a cut carries more than N chords, two crossing chords have
    // intersecting spans on the other axis (pigeonhole in N coordinates).
    // Reconnecting these on either side of the bad cut strictly decreases
    // excess there and cannot increase any cut on the other axis.
    void repair(Matching& s) {
        while(x.overloaded || y.overloaded) {
            int best_x=-1, best_y=0, best_d=0, best_g=1;
            for(int i=0; i<s.n; ++i) if(i<s.p[i])
                for(int j=i+1; j<s.n; ++j) if(i<s.p[j]) {
                    int u=s.p[i],v=s.p[j];
                    int gain=x.overload_gain(x.change(i,j,u,v))+y.overload_gain(y.change(i,j,u,v));
                    if(gain<=0) continue;
                    int d=s.delta(i,j);
                    if(best_x<0 || d*best_g<best_d*gain) {
                        best_x=i; best_y=j; best_g=gain; best_d=d;
                    }
                }
            if(best_x<0) return;
            int u=s.p[best_x], v=s.p[best_y];
            x.apply(x.change(best_x,best_y,u,v)); y.apply(y.change(best_x,best_y,u,v));
            s.exchange(best_x,best_y,best_d);
        }
    }
};

} // namespace pairing_detail

// a may contain ranks either 0..n-1 or 1..n. effort=0 uses the assignment
// alone, effort>=1 also refines the exact inversion count of the receiver array.
inline std::vector<int> optimize_pairing(const std::vector<int>& input, unsigned seed, int effort, bool feasible) {
    using namespace pairing_detail;
    int n = input.size();
    if (n == 0) return {};
    std::vector<int> a = input;
    int minimum = *std::min_element(a.begin(), a.end());
    for (int& v : a) v -= minimum;
    std::vector<int> penalty(n), cost(n*n);
    for (int i=0; i<n; ++i) penalty[i] = int(64*std::sqrt(100.0 + i*i));
    for (int i=0; i<n; ++i)
        for (int j=0; j<n; ++j)
            cost[i*n+j] = penalty[std::abs(i-a[j])] + penalty[std::abs(j-a[i])];
    auto best = initial(a,cost);
    if (n<=2 || (effort<=0 && !feasible)) return best;
    Matching s(a,best);
    BoardCuts cuts(best);
    if (feasible) {
        cuts.repair(s);
        best=s.p;
    }
    if(effort<=0) return best;

    const int k = std::min(n-1, 32);
    std::vector<int> near(n*k), row(n);
    std::iota(row.begin(),row.end(),0);
    for (int x=0; x<n; ++x) {
        cost[x*n+x] = 1000000000;
        const int* c = &cost[x*n];
        std::partial_sort(row.begin(),row.begin()+k,row.end(),[&](int i,int j){return c[i]<c[j];});
        std::copy_n(row.begin(),k,near.begin()+x*k);
    }

    Random rng{seed ? seed : 1};
    int best_inv = s.inv;
    for (int pass = 0; pass < effort; ++pass) {
        if (pass != 0) {
            auto restarted = Matching(a,best);
            s.p.swap(restarted.p); s.b.swap(restarted.b); s.prefix.swap(restarted.prefix);
            s.inv = best_inv;
            if(feasible) cuts=BoardCuts(best);
        }
        constexpr int stages = 32;
        for (int stage = 0; stage < stages; ++stage) {
            double temp = (pass ? 4.0 : 8.0) * std::pow(0.045, double(stage)/(stages-1));
            std::array<uint32_t,128> 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<int> choose_partners(const std::vector<int>& 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<int> choose_feasible_partners(const std::vector<int>& a,unsigned seed=1,int effort=1) {
    return optimize_pairing(a,seed,effort,true);
}

} // namespace spectrum

using namespace std;

namespace routing {

vector<int> straight(int n) {
    vector<int> mate(4*n);
    for (int i=0; i<n; ++i) {
        mate[i] = 3*n-1-i;
        mate[mate[i]] = i;
        mate[n+i] = 4*n-1-i;
        mate[mate[n+i]] = n+i;
    }
    return mate;
}

// slack[g][h] is half the spare capacity of the boundary interval (g,h].
// The all-straight drawing of the remaining grid gives its min-cut capacity.
bool draw(int n, vector<int> mate, vector<string>& board) {
    const int m = 4*n;
    auto cap = straight(n);
    vector<short> slack(m*m);
    vector<int> ring(2*m);
    for (int i=0; i<2*m; ++i) ring[i]=i%m;
    for (int g=0; g<m; ++g) {
        int a=0,b=0;
        for (int h=g+1; h<g+m; ++h) {
            int k=ring[h];
            auto entered = [&](int j) {
                int d=j-g;
                if (d<=0) d+=m;
                return d<=h-g;
            };
            a += entered(cap[k]) ? -1 : 1;
            b += entered(mate[k]) ? -1 : 1;
            if (a<b) return false;
            slack[g*m+k]=(a-b)/2;
        }
    }
    auto exchange = [](vector<int>& 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<int> reach(m);
    for (int y=0; y<n; ++y) for (int x=0; x<n; ++x) {
        int p=(m-1-y+x)%m, q=ring[p+1];
        int* pos=ring.data()+p;
        auto offset = [p,m](int i){return i>=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 (u<v) {
                // The target strands cross. Realize their first crossing.
                for (int i=u; i<v; ++i) change(p,pos[i],1);
                exchange(mate,p,q);
            } else {
                // The target order is already correct on the new frontier.
                board[y][x]='2';
            }
        } else {
            board[y][x]='1';
            int low=b, high=a-1;
            for (int i=a; i<b; ++i) if (slack[p*m+pos[i]]==0) {
                low=min(low,i);
                high=i;
            }
            if (low<=high) {
                // Joining the two incoming rays frees the outgoing pair.
                // Split a target chord across every tight cut at this corner.
                // No outside tight interval may contain both split endpoints.
                int farthest=0;
                for (int left=1; left<low; ++left) {
                    auto* s=slack.data()+pos[left]*m;
                    for (int right=m-1; right>farthest; --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<v; ++i) change(p,pos[i],1);
                for (int l=1; l<u; ++l)
                    for (int r=v; r<m; ++r) change(pos[l],pos[r],-1);
                int r=pos[u], s=pos[v];
                mate[q]=r; mate[r]=q;
                mate[p]=s; mate[s]=p;
            }
        }
        for (int i=a; i<b; ++i) change(p,pos[i],-1);
    }
    return mate==cap;
}

bool realizes(const vector<string>& board, const vector<int>& 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<m;++i) {
        int r,c,d;
        if (i<n) {r=0;c=i;d=2;}
        else if (i<2*n) {r=i-n;c=n-1;d=3;}
        else if (i<3*n) {r=n-1;c=3*n-1-i;d=0;}
        else {r=4*n-1-i;c=0;d=1;}
        while (r>=0 && r<n && c>=0 && c<n) {
            char s=board[r][c];
            if (s=='1') d^=1;
            if (s=='2') d^=3;
            r+=dy[d];c+=dx[d];
        }
        int j=r<0 ? c : 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<int> a(4*n);
    for (int& v:a) {cin>>v;--v;}
    vector<string> 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<<row<<'\n';
}
#endif


namespace triple_search {
using spectrum::pairing_detail::Matching;
using spectrum::pairing_detail::BoardCuts;
using spectrum::pairing_detail::AxisCuts;
using spectrum::pairing_detail::Random;
using Time=chrono::steady_clock;

struct CycleSearch {
    const vector<int>& a;
    int m, width;
    Matching s;
    BoardCuts cuts;
    Random rng;
    vector<short> raw;
    vector<vector<int>> near;

    CycleSearch(const vector<int>& ranks,const vector<int>& 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<m;++i) {
            auto& n=near[i];
            for(int j=0;j<m;++j) if(i!=j)n.push_back(j);
            auto metric=[&](int j) {
                int dx=a[i]-j,dy=a[j]-i;
                return dx*dx+dy*dy;
            };
            int k=min(48,m-1);
            partial_sort(n.begin(),n.begin()+k,n.end(),[&](int j,int l){return metric(j)<metric(l);});
            n.resize(k);
        }
    }

    // Count inversions against the frozen sequence when rank t is placed at i.
    int contribution(int i,int t) const {
        return i-s.less(i,t+1)+t-s.less(i+1,t);
    }
    void prepare() {
        vector<int> before(m);
        for(int i=0;i<m;++i) before[i]=contribution(i,s.b[i]);
        for(int i=0;i<m;++i) for(int j=0;j<i;++j) {
            int d=contribution(i,a[j])+contribution(j,a[i])-before[i]-before[j];
            raw[i*m+j]=raw[j*m+i]=d;
        }
        for(int i=0;i<m;++i) {
            auto& n=near[i];
            partial_sort(n.begin(),n.begin()+width,n.end(),[&](int x,int y){
                return raw[i*m+x]<raw[i*m+y];
            });
        }
    }
    // If both endpoints of an inversion term move, undo the two one-sided
    // contributions, then add the joint change exactly once.
    int delta(int x,int y,int z,int linear) const {
        int u=s.p[x],v=s.p[y],w=s.p[z];
        int i[6]={x,y,z,u,v,w};
        int b[6]={a[v],a[w],a[u],a[z],a[x],a[y]};
        for(int j=1;j<6;++j)for(int k=0;k<j;++k) {
            int oldj=s.b[i[j]],oldk=s.b[i[k]];
            if(i[j]<i[k])
                linear+=(b[j]>b[k])+(oldj>oldk)-(oldj>b[k])-(b[j]>oldk);
            else
                linear+=(b[j]<b[k])+(oldj<oldk)-(oldj<b[k])-(b[j]<oldk);
        }
        return linear;
    }
    // These three chords give a load change of at most two on every line.
    // A reduction by the second switch can cancel the first switch's increase.
    bool axis_permits(const AxisCuts& axis,int x,int y,int z) const {
        int u=s.p[x],v=s.p[y],w=s.p[z];
        auto first=axis.change(x,y,u,v), second=axis.change(y,z,u,w);
        uint64_t added=first.add | second.add;
        uint64_t removed=first.remove | second.remove;
        return !(added & ~removed & axis.saturated);
    }
    bool permits(int x,int y,int z) const {
        return axis_permits(cuts.x,x,y,z) && axis_permits(cuts.y,x,y,z);
    }
    void elementary(int x,int y) {
        int u=s.p[x],v=s.p[y];
        cuts.x.apply(cuts.x.change(x,y,u,v));cuts.y.apply(cuts.y.change(x,y,u,v));
        s.exchange(x,y,s.delta(x,y));
    }
    void cycle(int x,int y,int z) { elementary(x,y); elementary(y,z); }

    bool descend() {
        prepare();
        int bx=0,by=0,bz=-1,bd=0;
        for(int x=0;x<m;++x) for(int y=x+1;y<m;++y) {
            if(s.p[x]==y || x>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<m;++x) for(int j=0;j<width;++j) {
            int v=near[x][j],y=s.p[v],u=s.p[x];
            if(u==v)continue;
            int d0=raw[x*m+v];
            for(int k=0;k<width;++k) {
                int w=near[y][k],z=s.p[w];
                if(w==u || w==x || w==v)continue;
                int linear=d0+raw[y*m+w]+raw[z*m+u];
                if(linear-15>=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<int> refine(const vector<int>& a,const vector<int>& 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()<deadline) {
        if(engine.descend()) {
            if(engine.s.inv<best_inv) {best_inv=engine.s.inv;best=engine.s.p;stalls=0;}
        } else {
            if(engine.s.inv>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<int> 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<string> 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<<row<<'\n';
}
#endif


#include <chrono>
#include <limits>

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<<limit];
    int rest_load[2][64]{};
    int coord[2][limit], side;

    inline int pair_term(int i,int j,int x,int y) const {
        return ((i<j)!=(rank[x]<rank[y]));
    }
    int interaction(int i,int j,int k,int l) const {
        return pair_term(i,k,j,l)+pair_term(i,l,j,k)+pair_term(j,k,i,l)+pair_term(j,l,i,k);
    }

    int bound(int mask) {
        int& ans=memo[mask];
        if(ans>=0) return ans;
        int i=__builtin_ctz(mask);
        int remain=mask^(1<<i);
        ans=std::numeric_limits<int>::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<<j)));
        }
        return ans;
    }

    bool feasible() const {
        for(int axis=0; axis<2; ++axis) {
            int diff[65]{};
            for(int i=0; i<size; ++i) if(i<choice[i]) {
                int a=coord[axis][i], b=coord[axis][choice[i]];
                ++diff[std::min(a,b)]; --diff[std::max(a,b)];
            }
            int count=0;
            for(int k=0; k<side-1; ++k) {
                count+=diff[k];
                if(rest_load[axis][k]+count>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<<i);
        for(int t=0; t<size-1; ++t) {
            int j=order[i][t], bit=1<<j;
            if(!(bit&remain)) continue;
            int next=remain^bit;
            int added=unary[i][j];
            if(partial+added+bound(next)>=best_cost) continue;
            for(int k=0; k<i; ++k) if(k<choice[k])
                added+=interaction(i,j,k,choice[k]);
            choice[i]=j; choice[j]=i;
            explore(next,partial+added);
            if(visits>1700) break;
        }
    }

    bool refine(Matching& s,BoardCuts& cuts,const std::vector<int>& picked) {
        size=picked.size(); full=(1<<size)-1; side=cuts.x.side;
        std::copy_n(picked.begin(),size,node);
        std::sort(node,node+size);
        for(int i=0;i<size;++i) {
            rank[i]=s.a[node[i]];
            original[i]=std::lower_bound(node,node+size,s.p[node[i]])-node;
            result[i]=original[i];
        }
        for(int axis=0;axis<2;++axis) {
            const AxisCuts& c=axis?cuts.y:cuts.x;
            for(int k=0;k<side;++k) rest_load[axis][k]=c.load_at(k);
            for(int i=0;i<size;++i) coord[axis][i]=c.coord[node[i]];
            for(int i=0;i<size;++i) if(i<original[i]) {
                int a=coord[axis][i],b=coord[axis][original[i]];
                for(int k=std::min(a,b);k<std::max(a,b);++k) --rest_load[axis][k];
            }
        }
        int frozen[limit][limit];
        for(int j=0;j<size;++j) {
            int v=rank[j], subset_less=0;
            for(int i=0;i<size;++i) subset_less+=rank[i]<v;
            int left_subset_less=0;
            for(int i=0;i<size;++i) {
                int x=node[i], left=x-i;
                int less_left=s.less(x,v)-left_subset_less;
                frozen[i][j]=left+v-subset_less-2*less_left;
                left_subset_less+=s.b[x]<v;
            }
        }
        best_cost=0;
        for(int i=0;i<size;++i) {
            int t=0;
            for(int j=0;j<size;++j) if(i!=j) {
                unary[i][j]=frozen[i][j]+frozen[j][i]+pair_term(i,j,j,i);
                order[i][t++]=j;
            }
            std::sort(order[i],order[i]+t,[&](int a,int b){return unary[i][a]<unary[i][b];});
            int j=original[i];
            if(i<j) {
                best_cost+=unary[i][j];
                for(int k=0;k<i;++k) if(k<original[k]) best_cost+=interaction(i,j,k,original[k]);
            }
        }
        int starting=best_cost;
        std::fill_n(memo,full+1,-1); memo[0]=0; visits=0;
        explore(full,0);
        if(best_cost==starting) return false;
        for(int i=0;i<size;++i) {
            int x=node[i],v=node[result[i]];
            if(s.p[x]==v) continue;
            int y=s.p[v],u=s.p[x];
            cuts.x.apply(cuts.x.change(x,y,u,v)); cuts.y.apply(cuts.y.change(x,y,u,v));
            s.exchange(x,y,s.delta(x,y));
        }
        return true;
    }
};

inline std::vector<int> nearest(const std::vector<int>& a,int count,bool reflected) {
    int n=a.size();
    std::vector<int> table(n*count),ord(n),cost(n);
    std::iota(ord.begin(),ord.end(),0);
    for(int i=0;i<n;++i) {
        for(int j=0;j<n;++j) {
            int dx=reflected?i-a[j]:i-j;
            int dy=reflected?a[i]-j:a[i]-a[j];
            cost[j]=dx*dx+dy*dy;
        }
        cost[i]=1000000000;
        std::partial_sort(ord.begin(),ord.begin()+count,ord.end(),[&](int l,int r){return cost[l]<cost[r];});
        std::copy_n(ord.begin(),count,table.begin()+i*count);
    }
    return table;
}

inline int total_excess(const BoardCuts& cuts) {
    int excess=0;
    for(int k=0;k<cuts.x.side-1;++k)
        excess+=std::max(0,cuts.x.load_at(k)-cuts.x.side)+std::max(0,cuts.y.load_at(k)-cuts.y.side);
    return excess/2;
}

inline void anneal(Matching& s,BoardCuts& cuts,Random& rng,const std::vector<int>& neighbors,int count,
                   int& best_inv,std::vector<int>& 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<stages;++stage) {
        double temp=initial_t*std::pow(0.04,double(stage)/(stages-1));
        bool soft=round%4!=1 && stage<13;
        int price=3+stage;
        std::array<uint32_t,160> 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<best_inv) {best_inv=s.inv;best=s.p;}
        }
    }
    if(bad) cuts.repair(s);
}

inline std::vector<int> cluster_nodes(const Matching& s,Random& rng,const std::vector<int>& 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<int> nodes{anchor,s.p[anchor]},pool;
    pool.reserve(count);
    for(int t=0;t<count;++t) pool.push_back(nearby[anchor*count+t]);
    for(int i=0;i<count && int(nodes.size())<2*pairs;++i) {
        int j=i+rng.index(std::min(5,count-i));
        std::swap(pool[i],pool[j]);
        int p=pool[i];
        if(std::find(nodes.begin(),nodes.end(),p)!=nodes.end()) continue;
        nodes.push_back(p);nodes.push_back(s.p[p]);
    }
    return nodes;
}

} // namespace advanced_detail

// The relative time budget includes matching construction. Routing time is separate.
inline std::vector<int> choose_advanced_partners(const std::vector<int>& 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<int> 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<int> current=best;
    Cluster cluster;
    for(int round=0;Clock::now()<end;++round) {
        Matching s(a,round%3==0?current:best);
        BoardCuts cuts(s.p);
        if(round>0) anneal(s,cuts,rng,proposals,count,best_inv,best,round);
        if(s.inv<best_inv) {best_inv=s.inv;best=s.p;}
        for(int it=0;it<60;++it) {
            if((it & 7)==0 && Clock::now()>=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<best_inv) {best_inv=s.inv;best=s.p;}
        }
        current=s.p;
    }
    return best;
}

} // namespace spectrum


namespace breeding {
using spectrum::pairing_detail::BoardCuts;
using spectrum::pairing_detail::Matching;
using spectrum::pairing_detail::Random;
using Clock = chrono::steady_clock;
using Deadline = Clock::time_point;

struct Individual {
    int inv;
    vector<int> 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<int>& a;
    int n, count=0, cutCount=0, best, work=0;
    uint64_t solution=0;
    vector<int> 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<int>& 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<n;++i) if(cycle[i]<0 && first.p[i]!=second.p[i]) {
            int x=i;
            do {
                cycle[x]=count; x=first.p[x];
                cycle[x]=count; x=second.p[x];
            } while(x!=i);
            ++count;
        }
        if(second.inv<best) {
            best=second.inv;
            solution=count==64 ? ~uint64_t(0) : (uint64_t(1)<<count)-1;
        }
    }
    void terms() {
        vector<int> old(n),alt(n);
        for(int i=0;i<n;++i) {old[i]=a[first.p[i]];alt[i]=a[second.p[i]];}
        // Every positional inversion is a function of at most two cycle bits.
        for(int i=0;i<n;++i) for(int j=i+1;j<n;++j) {
            int u=cycle[i],v=cycle[j];
            if(u<0 && v<0) continue;
            int f00=old[i]>old[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<n;++i) if(cycle[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;k<axis->side-1;++k) {
                int worst=axis->load_at(k);
                for(int u=0;u<count;++u) {
                    if(k) diff[u][k]+=diff[u][k-1];
                    worst+=max(0,diff[u][k]);
                }
                if(worst<=axis->side) 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<count;++u) changes[u][cutCount]=diff[u][k];
                ++cutCount;
            }
        }
    }
    void prepare() {
        terms();capacity();
        vector<int> strength(count);
        for(int u=0;u<count;++u) {
            strength[u]=abs(unary[u]);
            for(int v=0;v<count;++v) strength[u]+=abs(interaction[u][v]);
            for(int k=0;k<cutCount;++k) strength[u]+=abs(changes[u][k]);
            order[u]=u;linear[u]=unary[u];
        }
        sort(order,order+count,[&](int x,int y){return strength[x]>strength[y];});
        for(int i=count-1;i>=0;--i) {
            int u=order[i];
            for(int j=i+1;j<count;++j) futureDiscount[u]+=min(0,interaction[u][order[j]]);
            for(int k=0;k<cutCount;++k)
                minTail[i][k]=minTail[i+1][k]+min(0,changes[u][k]);
        }
    }
    void search(int depth,int inv,uint64_t mask) {
        if(++work>14000) return;
        if(!(work&255) && Clock::now()>=deadline) {work=15000;return;}
        int lower=inv;
        for(int j=depth;j<count;++j) {
            int u=order[j];
            lower+=min(0,linear[u]+futureDiscount[u]);
        }
        if(lower>=best) return;
        for(int k=0;k<cutCount;++k) if(loads[k]+minTail[depth][k]>0) return;
        if(depth==count) {best=inv;solution=mask;return;}
        int u=order[depth];
        auto select=[&]() {
            for(int j=depth+1;j<count;++j) linear[order[j]]+=interaction[u][order[j]];
            for(int k=0;k<cutCount;++k) loads[k]+=changes[u][k];
            search(depth+1,inv+linear[u],mask|(uint64_t(1)<<u));
            for(int k=0;k<cutCount;++k) loads[k]-=changes[u][k];
            for(int j=depth+1;j<count;++j) linear[order[j]]-=interaction[u][order[j]];
        };
        if(linear[u]<0) {select();search(depth+1,inv,mask);}
        else {search(depth+1,inv,mask);select();}
    }
    Individual run() {
        if(count<2) return first.inv<=second.inv?first:second;
        prepare();
        search(0,first.inv,0);
        Individual result{best,first.p};
        for(int i=0;i<n;++i) if(cycle[i]>=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<int>(),not_equal_to<int>());
}
void admit(vector<Individual>& 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(d<minDistance) {minDistance=d;close=i;}
    }
    if(minDistance<10) {
        if(pool[close].inv<=child.inv) return;
        pool[close]=move(child);
    } else {
        pool.push_back(move(child));
        if(pool.size()>12) {
            int remove=-1, largest=INT_MIN;
            int leader=min_element(pool.begin(),pool.end(),[](const auto& a,const auto& b){
                return a.inv<b.inv;
            })-pool.begin();
            for(int i=0;i<(int)pool.size();++i) if(i!=leader) {
                int near=INT_MAX;
                for(int j=0;j<(int)pool.size();++j) if(j!=i) near=min(near,distance(pool[i],pool[j]));
                int rating=3*pool[i].inv-min(near,60);
                if(rating>largest) {largest=rating;remove=i;}
            }
            pool.erase(pool.begin()+remove);
        }
    }
    sort(pool.begin(),pool.end(),[](const auto& a,const auto& b){return a.inv<b.inv;});
}
Individual assessed(const vector<int>& a,vector<int> p) {
    int inv=Matching(a,p).inv;
    return {inv,move(p)};
}
vector<int> optimize(const vector<int>& 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<Individual> pool{initial};
    admit(pool,move(alternate));
    Deadline evolutionEnd=start+chrono::milliseconds(1510);
    Deadline searchEnd=start+chrono::milliseconds(1815);
    for(int generation=0;Clock::now()<evolutionEnd;++generation) {
        int parent=min(rng.index(pool.size()),rng.index(pool.size()));
        if(generation%6==0) parent=pool.size()-1;
        const auto& anchor=pool[parent];
        Matching s(a,anchor.p);
        BoardCuts cuts(s.p);
        int bestInv=INT_MAX;
        vector<int> 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()<polish)
            child=assessed(a,triple_search::refine(a,child.p,polish,rng.next()));
        auto pooled=child;
        vector<int> 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<pooled.inv) pooled=move(mix);
        }
        admit(pool,move(child));
        admit(pool,move(pooled));
    }
    return triple_search::refine(a,pool.front().p,searchEnd,rng.next());
}
}

#ifndef SPECTRUM_CROSS_LIBRARY
int main() {
    const auto start=chrono::steady_clock::now();
    ios::sync_with_stdio(false); cin.tie(nullptr);
    int n;
    if(!(cin>>n)) return 0;
    vector<int> a(4*n);
    for(int& v:a) {cin>>v;--v;}
    auto target=breeding::optimize(a,start);
    vector<string> board;
    if(!routing::draw(n,target,board) || !routing::realizes(board,target))
        board.assign(n,string(n,'0'));
    for(const auto& row:board) cout<<row<<'\n';
}
#endif



namespace spectrum {
namespace global_detail {

using namespace advanced_detail;

inline std::vector<int> assignment(const std::vector<int>& c,int n) {
    std::vector<int> owner(n+1),prev(n+1),u(n+1),v(n+1),d(n+1),ans(n);
    std::vector<char> 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<d[j]) {d[j]=s;prev[j]=k;}
                if(d[j]<shift) {shift=d[j];next=j;}
            }
            for(int j=0;j<=n;++j) {
                if(used[j]) {u[owner[j]]+=shift;v[j]-=shift;}
                else d[j]-=shift;
            }
            k=next;
        } while(owner[k]);
        do {
            int j=prev[k];owner[k]=owner[j];k=j;
        } while(k);
    }
    for(int j=1;j<=n;++j)ans[owner[j]-1]=j-1;
    return ans;
}

inline void exchange(Matching& s,BoardCuts& cuts,int a,int b) {
    int u=s.p[a], v=s.p[b];
    cuts.x.apply(cuts.x.change(a,b,u,v));cuts.y.apply(cuts.y.change(a,b,u,v));
    s.exchange(a,b,s.delta(a,b));
}

struct CycleSearch {
    int best_inv;
    std::vector<int> 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<int> l,r;
        for(int i=0;i<s.n;++i) if(i<s.p[i] && int(rng.index(100))<keep) {
            int a=i,b=s.p[i];
            if(a-s.a[a]>b-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<int> where(s.n),c(m*m);
        for(int i=0;i<s.n;++i)where[s.b[i]]=i;
        auto frozen=[&](int p,int v) {
            return p+v-2*s.less(p,v)-(where[v]<p)-(s.b[p]<v);
        };
        auto inv=[](int i,int x,int j,int y){return i<j ? x>y : y>x;};
        int price[2][65]{};
        int shadow=phase%4==0?0:1+rng.index(16);
        for(int k=0;k<cuts.x.side-1;++k) {
            price[0][k+1]=price[0][k]+shadow*(cuts.x.load_at(k)==cuts.x.side);
            price[1][k+1]=price[1][k]+shadow*(cuts.y.load_at(k)==cuts.y.side);
        }
        const int noise=1+rng.index(phase%4==3?112:48);
        for(int i=0;i<m;++i)for(int j=0;j<m;++j) {
            int p=l[i],q=r[j],v=s.a[q],w=s.a[p];
            int incident=frozen(p,v)+frozen(q,w)-inv(p,v,q,s.b[q])-inv(q,w,p,s.b[p])+inv(p,v,q,w);
            int cap=std::abs(price[0][cuts.x.coord[p]]-price[0][cuts.x.coord[q]])
                   +std::abs(price[1][cuts.y.coord[p]]-price[1][cuts.y.coord[q]]);
            c[i*m+j]=8*incident+cap+rng.index(noise);
        }
        auto dest=assignment(c,m);
        std::vector<char> seen(m);
        std::vector<int> cycle;
        for(int start=0;start<m;++start) if(!seen[start]) {
            cycle.clear();
            for(int j=start;!seen[j];j=dest[j]) {seen[j]=1;cycle.push_back(l[j]);}
            if(cycle.size()<2) continue;
            int old=s.inv;
            for(size_t j=1;j<cycle.size();++j)exchange(s,cuts,cycle[j-1],cycle[j]);
            bool good=!cuts.x.overloaded && !cuts.y.overloaded;
            int d=s.inv-old;
            if(good && (d<=0 || (phase%5==4 && d<=6 && rng.index(16)<3))) {
                if(s.inv<best_inv){best_inv=s.inv;best=s.p;}
            } else {
                for(int j=int(cycle.size())-1;j>0;--j)exchange(s,cuts,cycle[j-1],cycle[j]);
            }
        }
    }
};

} // namespace global_detail

inline std::vector<int> choose_global_partners(const std::vector<int>& 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::vector<int>a=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<n;++i){
        identity&=a[i]==i;
        exact&=a[i]!=i && a[a[i]]==i;
    }
    if(identity){
        std::vector<int> p(n);
        for(int i=0;i<n;++i)p[i]=i^1;
        return p;
    }
    if(exact) {
        BoardCuts cuts(a);
        if(!cuts.x.overloaded && !cuts.y.overloaded)return a;
    }
    auto p=choose_feasible_partners(a,seed,milliseconds>=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()<end;++round) {
        Matching s(a,round%3?search.best:p);
        BoardCuts cuts(s.p);
        if(round>0)anneal(s,cuts,rng,proposals,count,search.best_inv,search.best,round);
        if(s.inv<search.best_inv) {search.best_inv=s.inv;search.best=s.p;}
        for(int it=0;it<30 && Clock::now()<end;++it) {
            if(it%3==0) search.step(s,cuts,rng,it/3+round);
            else {
                auto nodes=cluster_nodes(s,rng,nearby,count,std::min(n/2,int(5+rng.index(4))));
                if(cluster.refine(s,cuts,nodes) && s.inv<search.best_inv) {search.best_inv=s.inv;search.best=s.p;}
            }
        }
        p=s.p;
    }
    return search.best;
}

} // namespace spectrum


namespace portfolio {
using spectrum::pairing_detail::Matching;
using spectrum::pairing_detail::BoardCuts;
using spectrum::pairing_detail::Random;
using spectrum::advanced_detail::Cluster;
using spectrum::global_detail::CycleSearch;
using breeding::Individual;
using Clock=std::chrono::steady_clock;
using Deadline=Clock::time_point;

// Stop with a valid incumbent when the input makes the initial cut repair
// unusually expensive. Each completed iteration reduces total excess.
bool repair(Matching& s,BoardCuts& cuts,Deadline end) {
    while(cuts.x.overloaded || cuts.y.overloaded) {
        int bx=-1,by=0,bd=0,bg=1;
        for(int i=0;i<s.n;++i) {
            if((i&15)==0 && Clock::now()>=end) return false;
            if(i>=s.p[i])continue;
            for(int j=i+1;j<s.n;++j) if(i<s.p[j]) {
                int u=s.p[i],v=s.p[j];
                auto cx=cuts.x.change(i,j,u,v),cy=cuts.y.change(i,j,u,v);
                int gain=cuts.x.overload_gain(cx)+cuts.y.overload_gain(cy);
                if(gain<=0)continue;
                int d=s.delta(i,j);
                if(bx<0 || d*bg<bd*gain) {bx=i;by=j;bd=d;bg=gain;}
            }
        }
        if(bx<0)return false;
        spectrum::global_detail::exchange(s,cuts,bx,by);
    }
    return true;
}

struct Incumbent {
    int n,inv;
    vector<string> board;
    vector<int> partners;
    Incumbent(int side,const vector<int>& a)
        : n(side),inv(Matching(a,routing::straight(n)).inv),board(n,string(n,'0')),partners(routing::straight(n)) {}
    void consider(const vector<int>& a,const vector<int>& p) {
        int score=Matching(a,p).inv;
        if(score>=inv)return;
        vector<string> 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<int>& nearby,
            const vector<int>& proposals,int width,int round,bool regional,
            CycleSearch& best,Deadline end) {
    int bad=spectrum::advanced_detail::total_excess(cuts);
    vector<int> 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<min(width,23);++j) {
            int z=nearby[x*width+j];
            focus.push_back(z);focus.push_back(s.p[z]);
        }
    }
    int start_temp=regional?13:round%5==0?19:round%3==0?10:6;
    for(int stage=0;stage<20 && Clock::now()<end;++stage) {
        double temp=start_temp*pow(.04,stage/19.);
        int price=3+stage;
        bool soft=round%4!=1 && stage<13;
        array<uint32_t,160> 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<best.best_inv) {best.best_inv=s.inv;best.best=s.p;}
        }
    }
}

// Both maps are bijections of the same physical terminals. In a reflected
// frame the ranks and positions reverse together; transposition interchanges
// them. Applying either operation preserves every pairwise inversion.
struct SearchFrame {
    vector<int> label,physical,ranks;
    SearchFrame(const vector<int>& a,bool transpose,bool reverse)
        : label(a.size()),physical(a.size()),ranks(a.size()) {
        int n=a.size();
        for(int x=0;x<n;++x) {
            int u=transpose?a[x]:x, v=transpose?x:a[x];
            if(reverse) {u=n-1-u;v=n-1-v;}
            label[x]=u;physical[u]=x;ranks[u]=v;
        }
    }
    vector<int> encode(const vector<int>& p) const {
        vector<int> q(p.size());
        for(int x=0;x<(int)p.size();++x)q[label[x]]=label[p[x]];
        return q;
    }
    vector<int> decode(const vector<int>& q) const {
        vector<int> 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<int> initial_family(const vector<int>& a,unsigned seed,bool perturb) {
    if(!perturb)return spectrum::choose_partners(a,1,0);
    int n=a.size();
    vector<int> cost(n*n), penalty(n);
    Random rng{seed};
    for(int i=0;i<n;++i)penalty[i]=int(64*sqrt(100.+i*i));
    for(int i=0;i<n;++i)for(int j=i+1;j<n;++j) {
        int distance=penalty[abs(i-a[j])]+penalty[abs(j-a[i])];
        cost[i*n+j]=cost[j*n+i]=distance+int(rng.index(321));
    }
    return spectrum::pairing_detail::initial(a,cost);
}

template<class Consider>
void run_phase(const vector<int>& a,const vector<int>& 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<Individual> pool{{best.best_inv,p}};
    Cluster cluster;
    auto checkpoint=start+chrono::milliseconds(180);
    for(int round=0;Clock::now()<search_end;++round) {
        // Keep an independent parent for the opening rounds of each family.
        // Later reflected rounds can search directly from the carried elite,
        // while p and the breeding pool retain the new family's trajectory.
        if(perturb && round==4 && warm) {
            breeding::admit(pool,*warm);
            if(warm->inv<best.best_inv) {
                best.best_inv=warm->inv;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.inv<best.best_inv){best.best_inv=s.inv;best.best=s.p;}
        int rounds=round%6==2?48:30;
        for(int it=0;it<rounds && Clock::now()<search_end;++it) {
            if(it%3==0 && round%6!=2)best.step(s,cuts,rng,it/3+round);
            else {
                auto nodes=spectrum::advanced_detail::cluster_nodes(s,rng,nearby,width,min(n/2,int(5+rng.index(4))));
                if(cluster.refine(s,cuts,nodes) && s.inv<best.best_inv) {
                    best.best_inv=s.inv;best.best=s.p;
                }
            }
        }
        p=s.p;
        Individual child{s.inv,s.p};
        if(breed && Clock::now()<search_end) {
            auto polished=triple_search::refine(a,child.p,min(search_end,Clock::now()+chrono::milliseconds(5)),rng.next());
            child=breeding::assessed(a,std::move(polished));
        }
        if(pool.size()>1 && Clock::now()<search_end) {
            auto mix=breeding::Recombination(a,child,pool[rng.index(pool.size())],search_end).run();
            if(mix.inv<child.inv)child=std::move(mix);
        }
        if(warm && round%5==2 && Clock::now()<search_end) {
            auto mix=breeding::Recombination(a,child,*warm,search_end).run();
            // A strict gain over both families can seed subsequent rounds.
            if(mix.inv<min(child.inv,warm->inv)) child=move(mix);
        }
        if(child.inv<best.best_inv){best.best_inv=child.inv;best.best=child.p;}
        breeding::admit(pool,std::move(child));
        if(round%5==4)breeding::admit(pool,{best.best_inv,best.best});
        if(Clock::now()>=checkpoint) {
            consider(best.best_inv,best.best);
            checkpoint=Clock::now()+chrono::milliseconds(380);
        }
    }
    consider(best.best_inv,best.best);
}
vector<string> solve(const vector<int>& 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<int> adjacent(n);
    for(int i=0;i<n;++i)adjacent[i]=i^1;
    bool identity=true,exact=true;
    for(int i=0;i<n;++i) {
        identity&=a[i]==i;
        exact&=a[i]!=i && a[a[i]]==i;
    }
    if(exact)incumbent.consider(a,a);
    if(incumbent.inv==0)return incumbent.board;
    if(identity) {incumbent.consider(a,adjacent);return incumbent.board;}
    constexpr unsigned seeds[]={1,0x72136ad5u,0xae212bbdu,0x83ab239fu};
    constexpr int finish_ms[]={500,990,1390,1808};
    for(int phase=0;phase<4 && incumbent.inv>0;++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<int>& p) {
            if(inv<incumbent.inv)incumbent.consider(a,frame.decode(p));
        };
        run_phase(frame.ranks,fallback,phase_start,phase_end,seeds[phase],
                  phase?&carry:nullptr,phase>=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<int> a(4*n);
    for(int& v:a){cin>>v;--v;}
    auto board=portfolio::solve(a,n,start);
    for(const auto& row:board)cout<<row<<'\n';
}
0