题解:P9731 [CEOI 2023] Balance

· · 题解

very cool problem。

部分分这么多,从部分分开始做肯定是有道理的。

一个方案是合法的当且仅当一个题在两个时刻评测次数相差不超过 $1$。这让我们联想到欧拉路径:入度出度之差不超过 $1$。因此我们重新刻画问题:在 $A, B$ 间连一条无向边,找出一条欧拉路径。那么沿着欧拉路径的方向定向,如果 $A$ 指向 $B$ 就把 $A$ 排在前面,否则 $B$ 排在前面。 现在考虑 $S = 2 ^ k$。这样可以想到分治:我们可以把所有时刻分成两半 $L, R$。我们能得到两个相差 $\le 1$ 的部分,继续递归下去,显然不会出现新的差距 $\ge 2$ 的两个时刻。因此就做完了。 ```cpp #include <bits/stdc++.h> using ll = long long; using ld = long double; using ull = unsigned long long; using namespace std; template <class T> using Ve = vector<T>; #define pii pair<ll, ll> #define rep(i, a, b) for(ll i = (a); i <= (b); ++i) #define per(i, a, b) for(ll i = (a); i >= (b); --i) #define pb push_back bool Mbe; ll read() { ll x = 0, f = 1; char ch = getchar(); while(ch < '0' || ch > '9') {if(ch == '-') f = -1; ch = getchar();} while(ch >= '0' && ch <= '9') x = x * 10 + ch - '0', ch = getchar(); return x * f; } void write(ll x) { if(x < 0) putchar('-'), x = -x; if(x > 9) write(x / 10); putchar(x % 10 + '0'); } const ll N = 5e5 + 9; ll n, S, T; Ve<Ve<ll> > a; Ve<pii> to[N]; pii e[N]; ll tote, path[N], plen, top[N]; bool vis[N], go[N]; ll cL, cM; void dfs(ll x) { go[x] = 1; while(top[x] < (ll)to[x].size()) { auto [y, w] = to[x][top[x]]; ll id = abs(w); ++top[x]; if(vis[id]) continue; vis[id] = 1; dfs(y); if(~e[id].first) { if(w < 0) { swap(a[e[id].first][cL + e[id].second], a[e[id].first][cM + 1 + e[id].second]); } } } } void solve(ll l, ll r) { if(l == r) return ; ll mid = (l + r) >> 1, len = mid - l + 1; cL = l, cM = mid; Ve<ll> pt; rep(i, 0, n - 1) { rep(j, l, r) pt.pb(a[i][j]); } pt.pb(0); sort(pt.begin(), pt.end()); pt.resize(unique(pt.begin(), pt.end()) - pt.begin()); rep(i, 0, tote) vis[i] = 0; tote = 0, plen = 0; for(ll x : pt) to[x].clear(), top[x] = 0, go[x] = 0; rep(i, 0, n - 1) { rep(j, 0, len - 1) { ll x = a[i][l + j], y = a[i][mid + 1 + j]; ++tote, e[tote] = {i, j}; to[x].pb({y, tote}), to[y].pb({x, -tote}); } } for(ll x : pt) { if(!x) continue; if(to[x].size() & 1) { ++tote, e[tote] = {-1, -1}; to[0].pb({x, tote}), to[x].pb({0, -tote}); } } for(ll x : pt) { if(!go[x]) dfs(x); } solve(l, mid), solve(mid + 1, r); } bool Med; int main() { cerr << fabs(&Med - &Mbe) / 1048576.0 << "MB\n"; n = read(), S = read(), T = read(); a = Ve<Ve<ll> > (n, Ve<ll>(S)); rep(i, 0, n - 1) { rep(j, 0, S - 1) a[i][j] = read(); } solve(0, S - 1); rep(i, 0, n - 1) { rep(j, 0, S - 1) write(a[i][j]), putchar(' '); putchar('\n'); } cerr << "\n" << clock() * 1.0 / CLOCKS_PER_SEC * 1000 << "ms\n"; return 0; } ```