結果
| 問題 | No.5026 Spectrum Router |
| コンテスト | |
| ユーザー |
prussian_coder
|
| 提出日時 | 2026-10-25 21:57:20 |
| 言語 | C++23(gcc16) (gcc 16.2.0 + boost 1.92.0 + ACL) |
| 結果 |
AC
不安定
|
| 実行時間 | 1,445 ms / 2,000 ms |
| + 31µs | |
| コード長 | 16,685 bytes |
| 記録 | |
| コンパイル時間 | 2,621 ms |
| コンパイル使用メモリ | 265,880 KB |
| 実行使用メモリ | 9,908 KB |
| スコア | 77,929 |
| 最終ジャッジ日時 | 2026-11-23 20:32:09 |
| 合計ジャッジ時間 | 80,001 ms |
|
ジャッジサーバーID (参考情報) |
judge6_0 / judge4_0 |
| 純コード判定しない問題か言語 |
(要ログイン)
| ファイルパターン | 結果 |
|---|---|
| other | AC * 50 |
ソースコード
// Astraに作ってもらった解法
// NOTE: Writer解のスコアが順位表に現れないように、あえてスコア最小化としている
// 問題の変換:鏡の配置を直接探索せず、160個のポートを80組のペアに分ける問題として考える。
// 実現可能性の判定:盤面を分割する3,042個の切断条件を使い、各切断をまたぐペア数が通路容量を超えないようにする。
// 近傍探索:2~6組のペアを組み替え、実現可能性を維持しながら、公式スコアを減らす。
// 焼きなまし法:スコアが悪化する変更も一定確率で採用し、局所最適解を脱出しながら探索する。
// 鏡の配置を構築:最良のペア構成から、平面グラフの経路構成アルゴリズムで光路を作り、各マスの鏡の向きを決定する。
// Spectrum Router: feasible perfect-matching search + exact planar routing.
// Build: g++ -std=c++17 -O3 -DNDEBUG main.cpp -o solver
// Run: ./solver < input.txt > output.txt
// The default wall-clock search budget is 1.45 seconds (for a 2-second limit).
//
// Routing reference: D. Wagner and K. Weihe,
// "A linear-time algorithm for edge-disjoint paths in planar graphs",
// Combinatorica 15(1), 135-150 (1995).
// https://math.mit.edu/~goemans/18438F09/wagnerweihe.pdf
#include <algorithm>
#include <array>
#include <chrono>
#include <cmath>
#include <cstdint>
#include <cstdlib>
#include <iomanip>
#include <iostream>
#include <limits>
#include <stdexcept>
#include <string>
#include <vector>
using namespace std;
using Clock = chrono::steady_clock;
struct Random {
uint64_t state = 2;
uint64_t next() { state ^= state << 7; state ^= state >> 9; return state; }
int below(int n) { return int(next() % uint64_t(n)); }
double unit() { return double(next() >> 11) * 0x1.0p-53; }
};
struct Options {
double seconds = 1.45;
uint64_t iterations = 0, seed = 1;
int cycles = 6;
bool large_moves = true;
};
Options parse_options(int argc, char** argv) {
Options o;
for (int i = 1; i < argc; ++i) {
string arg = argv[i];
auto value = [&]() -> string {
if (++i >= argc) throw invalid_argument("Missing option value");
return argv[i];
};
if (arg == "--time") o.seconds = stod(value());
else if (arg == "--iterations") o.iterations = stoull(value());
else if (arg == "--seed") o.seed = stoull(value());
else if (arg == "--cycles") o.cycles = stoi(value());
else if (arg == "--no-large-moves") o.large_moves = false;
else throw invalid_argument("Unknown option: " + arg);
}
if (!isfinite(o.seconds) || o.seconds <= 0 || o.cycles < 1)
throw invalid_argument("Invalid time budget or cycle count");
return o;
}
// A half-edge h=4*cell+side uses U=0, R=1, D=2, L=3.
// The two connections inside a cell are h <-> h XOR key[state].
struct Grid {
int n, m, cells;
vector<int> neighbor, entrance;
static constexpr int keys[3] = {2, 3, 1};
explicit Grid(int size) : n(size), m(4*n), cells(n*n),
neighbor(4*cells), entrance(m) {
constexpr int dr[4] = {-1,0,1,0}, dc[4] = {0,1,0,-1};
for (int r=0; r<n; ++r) for (int c=0; c<n; ++c)
for (int d=0; d<4; ++d) {
int rr=r+dr[d], cc=c+dc[d], h=4*(r*n+c)+d, p=-1;
if (rr<0) p=c;
else if (cc>=n) p=n+r;
else if (rr>=n) p=3*n-1-c;
else if (cc<0) p=4*n-1-r;
if (p>=0) { neighbor[h]=-p-1; entrance[p]=h; }
else neighbor[h]=4*(rr*n+cc)+(d^2);
}
}
int trace(const vector<int>& board, int port) const {
int h=entrance[port], steps=0;
while (h>=0) {
h=neighbor[h ^ keys[board[h/4]]];
if (++steps>4*cells) throw runtime_error("Trace failed to exit");
}
return -h-1;
}
// Return an empty vector exactly when the requested pairing cannot be routed.
// Phase 1 routes the noncrossing parenthesis matching and orients its edges.
// Phase 2 routes the original pairs in the resulting directed graph.
vector<int> route(const vector<int>& partner) const {
vector<int8_t> orientation(4*cells,0);
vector<uint8_t> used(4*cells,0);
vector<int> stack, closing, board(cells,0);
for (int t=m-1; t>=0; --t) {
if (partner[t]<t) { stack.push_back(t); continue; }
if (stack.empty()) return {};
int s=stack.back(); stack.pop_back(); closing.push_back(t);
int h=entrance[s]; orientation[h]=-1;
while (h>=0) {
int out=-1;
for (int d=1; d<4; ++d) {
int v=(h&~3) | ((h-d)&3);
if (!orientation[v]) { out=v; break; }
}
if (out<0) return {};
orientation[out]=1; h=neighbor[out];
if (h>=0) orientation[h]=-1;
}
if (-h-1!=t) return {};
}
for (int t : closing) {
int h=entrance[partner[t]]; used[h]=1;
while (h>=0) {
int out=-1;
for (int d=1; d<4; ++d) {
int v=(h&~3) | ((h-d)&3);
if (orientation[v]==1 && !used[v]) { out=v; break; }
}
if (out<0) return {};
int k=h^out;
board[h/4]=(k==2 ? 0 : k==3 ? 1 : 2);
used[out]=1; h=neighbor[out];
if (h>=0) used[h]=1;
}
if (-h-1!=t) return {};
}
// Always verify the returned board, independently of the cut data.
for (int p=0; p<m; ++p)
if (trace(board,p)!=partner[p]) return {};
return board;
}
};
// All nontrivial cut inequalities are opposite-side boundary-gap cuts.
// For gaps at coordinates t and b on opposite sides, capacity=n+abs(t-b).
// Slack is stored in units of TWO edges: all these slacks have even parity.
class CutConstraints {
int n, m, count, words;
vector<vector<uint64_t>> member;
vector<uint64_t> tight;
vector<int> slack;
void apply_bits(int word, uint64_t inc, uint64_t dec) {
while (inc) {
int bit=__builtin_ctzll(inc), id=64*word+bit;
if (--slack[id]==0) tight[word] |= uint64_t(1)<<bit;
inc &= inc-1;
}
while (dec) {
int bit=__builtin_ctzll(dec), id=64*word+bit;
if (slack[id]++==0) tight[word] &= ~(uint64_t(1)<<bit);
dec &= dec-1;
}
}
public:
explicit CutConstraints(int size) : n(size), m(4*n),
count(2*(n-1)*(n-1)), words((count+63)/64),
member(m,vector<uint64_t>(words,0)), tight(words,0), slack(count) {
int id=0;
for (int axis=0; axis<2; ++axis)
for (int t=1; t<n; ++t) for (int b=1; b<n; ++b,++id)
for (int p=0; p<m; ++p) {
int q=(p+axis*n)%m;
bool in=q<n ? q<t : q<2*n ? false :
q<3*n ? (3*n-1-q)<b : true;
if (in) member[p][id/64] |= uint64_t(1)<<(id%64);
}
}
void reset(const vector<int>& partner) {
fill(tight.begin(),tight.end(),0);
int id=0;
for (int axis=0; axis<2; ++axis)
for (int t=1; t<n; ++t) for (int b=1; b<n; ++b,++id) {
int crossing=0, word=id/64, bit=id%64;
for (int p=0; p<m; ++p) if (p<partner[p])
crossing += ((member[p][word]^member[partner[p]][word])>>bit)&1;
int s=n+abs(t-b)-crossing;
if (s<0 || (s&1)) throw runtime_error("Invalid cut slack");
slack[id]=s/2;
if (!s) tight[word] |= uint64_t(1)<<bit;
}
}
// Replace (a,b),(c,d) by (a,c),(b,d).
bool two(int a,int b,int c,int d,bool apply) {
for (int w=0; w<words; ++w) {
uint64_t ma=member[a][w], mb=member[b][w];
uint64_t mc=member[c][w], md=member[d][w];
uint64_t inc=~(ma^mb)&~(mc^md)&(ma^mc);
if (!apply) { if (inc&tight[w]) return false; }
else {
uint64_t dec=~(ma^mc)&~(mb^md)&(ma^mb);
apply_bits(w,inc,dec);
}
}
return true;
}
// Replace (x[i],y[i]) by (x[i],y[(i+1)%3]).
bool three(const int* x,const int* y,bool apply) {
for (int w=0; w<words; ++w) {
uint64_t a=member[x[0]][w], b=member[y[0]][w];
uint64_t c=member[x[1]][w], d=member[y[1]][w];
uint64_t e=member[x[2]][w], f=member[y[2]][w];
uint64_t o1=a^b,o2=c^d,o3=e^f;
uint64_t n1=a^d,n2=c^f,n3=e^b;
uint64_t old_high=(o1&o2)|(o2&o3)|(o3&o1);
uint64_t new_high=(n1&n2)|(n2&n3)|(n3&n1);
uint64_t inc=new_high&~old_high, dec=old_high&~new_high;
if (!apply) { if (inc&tight[w]) return false; }
else apply_bits(w,inc,dec);
}
return true;
}
// Bit-sliced exact crossing-count differences for 4--6-pair exchanges.
bool general(const int* x,const int* y,int k,bool apply) {
for (int w=0; w<words; ++w) {
uint64_t old_bits[4]={}, new_bits[4]={};
for (int j=0; j<k; ++j) {
uint64_t u=member[x[j]][w]^member[y[j]][w];
uint64_t v=member[x[j]][w]^member[y[(j+1)%k]][w];
for (int h=0; h<4; ++h) {
uint64_t a=old_bits[h]&u, b=new_bits[h]&v;
old_bits[h]^=u; new_bits[h]^=v; u=a; v=b;
}
}
// Parity is unchanged, so drop bit zero before subtraction.
uint64_t diff[4],borrow=0;
for (int h=0; h<3; ++h) {
diff[h]=new_bits[h+1]^old_bits[h+1]^borrow;
borrow=(~new_bits[h+1]&(old_bits[h+1]|borrow))|
(old_bits[h+1]&borrow);
}
diff[3]=borrow;
uint64_t changed=diff[0]|diff[1]|diff[2]|diff[3];
if (!apply) changed &= ~diff[3];
while (changed) {
int bit=__builtin_ctzll(changed), id=64*w+bit;
int delta=int((diff[0]>>bit)&1)+2*int((diff[1]>>bit)&1)+
4*int((diff[2]>>bit)&1)-8*int((diff[3]>>bit)&1);
if (!apply) { if (slack[id]<delta) return false; }
else {
if (!slack[id]) tight[w] &= ~(uint64_t(1)<<bit);
slack[id]-=delta;
if (!slack[id]) tight[w] |= uint64_t(1)<<bit;
}
changed &= changed-1;
}
}
return true;
}
};
int inversion_count(const vector<int>& b) {
int result=0;
for (int i=0; i<int(b.size()); ++i)
for (int j=i+1; j<int(b.size()); ++j) result += b[i]>b[j];
return result;
}
// Change b in place and return the EXACT change in its inversion count.
int swap_delta(vector<int>& b,int i,int j) {
if (i>j) swap(i,j);
int x=b[i],y=b[j],lo=min(x,y),hi=max(x,y),between=0;
for (int t=i+1; t<j; ++t) between += b[t]>lo && b[t]<hi;
swap(b[i],b[j]);
return x<y ? 1+2*between : -1-2*between;
}
int main(int argc,char** argv) {
ios::sync_with_stdio(false); cin.tie(nullptr);
try {
const Options opt=parse_options(argc,argv);
const auto start=Clock::now();
auto elapsed=[&]() { return chrono::duration<double>(Clock::now()-start).count(); };
int n;
if (!(cin>>n) || n<1 || n>100) throw invalid_argument("N must be in 1..100");
Grid grid(n); int m=grid.m;
vector<int> a(m),seen(m,0);
for (int& v:a) {
if (!(cin>>v) || v<1 || v>m || seen[v-1]++)
throw invalid_argument("A must be a permutation of 1..4N");
--v;
}
Random rng; rng.state=opt.seed+1; if (!rng.state) rng.state=1;
vector<int> partner(m),b(m),empty(grid.cells,0);
for (int p=0; p<m; ++p) { partner[p]=grid.trace(empty,p); b[p]=a[partner[p]]; }
const int max_score=m*(m-1)/2;
int inversions=inversion_count(b);
int score=max_score-inversions, best_score=score;
vector<int> best_partner=partner;
CutConstraints cuts(n); cuts.reset(partner);
vector<vector<int>> candidates(m);
for (int p=0; p<m; ++p) {
for (int q=0; q<m; ++q) if (p!=q) candidates[p].push_back(q);
sort(candidates[p].begin(),candidates[p].end(),[&](int x,int y) {
int wx=abs(a[p]-x)+abs(a[x]-p), wy=abs(a[p]-y)+abs(a[y]-p);
return wx!=wy ? wx<wy : x<y;
});
}
uint64_t iteration=0,accepted=0,invalid=0;
double temperature=30,progress=0; int phase=-1;
for (;;++iteration) {
if (!(iteration&255)) {
double now=elapsed();
if (now>=opt.seconds || (opt.iterations && iteration>=opt.iterations)) break;
progress=opt.iterations ? double(iteration)/opt.iterations : now/opt.seconds;
int cycle=min(opt.cycles-1,int(progress*opt.cycles));
double fraction=progress*opt.cycles-cycle;
if (cycle!=phase) {
phase=cycle;
if (cycle) {
partner=best_partner;
for (int p=0;p<m;++p) b[p]=a[partner[p]];
score=best_score;
inversions=max_score-score;
cuts.reset(partner);
}
}
double high=cycle ? 8.0 : 30.0;
temperature=high*pow(0.1/high,fraction);
}
int k=rng.below(100)<50 ? 3 : 2;
if (opt.large_moves && rng.below(100)<5) k=4+rng.below(3);
k=min(k,m/2);
int x[8],y[8],old_x[8],old_y[8]; bool duplicate=false;
x[0]=rng.below(m); y[0]=partner[x[0]];
for (int j=1;j<k;++j) {
int q;
if (rng.below(100)<85)
q=candidates[x[j-1]][rng.below(min(m-1,k>3 ? 12 : 24))];
else q=rng.below(m);
x[j]=partner[q]; y[j]=q;
for (int t=0;t<j;++t) if (x[j]==x[t] || x[j]==y[t]) duplicate=true;
}
if (duplicate) continue;
for (int j=0;j<k;++j) { old_x[j]=b[x[j]]; old_y[j]=b[y[j]]; }
int delta=0;
for (int j=0;j<k-1;++j) delta+=swap_delta(b,x[j],x[j+1]);
for (int j=1;j<k;++j) delta+=swap_delta(b,y[0],y[j]);
// delta は転倒数の変化量なので、スコアの変化量は -delta。
bool take=delta>=0 || rng.unit()<exp(double(delta)/temperature);
if (take) {
if (k==2) take=cuts.two(x[0],y[0],y[1],x[1],false);
else if (k==3) take=cuts.three(x,y,false);
else take=cuts.general(x,y,k,false);
if (!take) ++invalid;
}
if (!take) {
for (int j=0;j<k;++j) { b[x[j]]=old_x[j]; b[y[j]]=old_y[j]; }
continue;
}
if (k==2) cuts.two(x[0],y[0],y[1],x[1],true);
else if (k==3) cuts.three(x,y,true);
else cuts.general(x,y,k,true);
for (int j=0;j<k;++j) {
partner[x[j]]=y[(j+1)%k]; partner[y[(j+1)%k]]=x[j];
}
inversions+=delta;
score-=delta;
++accepted;
if (score<best_score) { best_score=score; best_partner=partner; }
}
vector<int> board=grid.route(best_partner);
if (board.empty()) throw runtime_error("Routing unexpectedly failed");
vector<int> verified(m);
for (int p=0;p<m;++p) verified[grid.trace(board,p)]=a[p];
if (max_score-inversion_count(verified)!=best_score)
throw runtime_error("Score verification failed");
for (int r=0;r<n;++r) {
for (int c=0;c<n;++c) cout<<board[r*n+c];
cout<<'\n';
}
cerr<<fixed<<setprecision(6)
<<"{\"score\":"<<best_score<<",\"inversions\":"<<max_score-best_score
<<",\"iterations\":"<<iteration<<",\"accepted\":"<<accepted
<<",\"infeasible_proposals\":"<<invalid<<",\"seconds\":"<<elapsed()
<<",\"seed\":"<<opt.seed<<",\"cycles\":"<<opt.cycles<<"}\n";
return 0;
} catch (const exception& e) {
cerr<<"Error: "<<e.what()<<'\n'; return 1;
}
}
prussian_coder