Dirt

· · 题解

Dilworth 转化后想了 1.5h+ 如何选出 n-K+1 条反链扣掉???成功被创飞。

考虑如何判定是否有解?套路的猜个充要条件,只考虑不能删除的格子,如果这些格子能选出 \ge K 的偏序链则一定不合法。必要性显然,充分性证明放到后面。

反难则正?选择点删除是不容易的,因为这样你的条件是剩余位置最小链覆盖 <K,于是直接选择 K-1 条反链,钦定这些位置保留,其余位置删除。

现在只有两个限制,反链必须全部包含不能被删除的位置,反链覆盖的点必须恰好是 n^2-(n-K+1)^2 个格子。

条件二较强,优先满足条件二。容易发现没有条件一的时候你直接钦定左上角一个 (K-1)\times(K-1) 的正方形不选,也就是这些反链形如若干个 L 型排布在右下角的时候个数是合法的。

考虑直接调整这些反链使之包含所有不能被删除的位置。

这也是容易的,因为如果只考虑不能被删除的位置,上面的充要条件已经保证了这些位置的最小反链覆盖是 <K 的,所以找到只考虑不能被删除的位置的最小反链覆盖再把它们“串”起来就行。

网格图的最小链覆盖可以贪心求解,类似迷宫的右手原则,分别把两维作为第一第二关键字排序按优先级选取就行(人话:选择的链尽量靠边),更为巧妙的是这样贪出来的链覆盖是不交的,也就保证了上面直接串不会串出两条反链相交的情况。

#include<bits/stdc++.h>
using ll = long long; using uint = unsigned int; using ull = unsigned long long;
#define cmd std::cerr
#define REQ(i, l, r) for (int i = l; i  < r; ++i)
#define REP(i, l, r) for (int i = l; i <= r; ++i)
#define PER(i, l, r) for (int i = l; i >= r; --i)
#define eb emplace_back
#define mset(a, v, n) memset((a), (v), sizeof((a)[0]) * (n))
const int N = 1e3 + 3, inf = 1e9 + 7; const uint P = 998244353; //
std::mt19937 rng(std::chrono::steady_clock::now().time_since_epoch().count() ^ (ull)new char);
int n, K, f[N][N], g[N][N]; bool vs[N][N]; std::string S[N]; std::set<int> st[N];
signed Create() {
    std::cin >> n >> K;
    REP(i, 1, n) std::cin >> S[i], S[i] = " " + S[i];
    PER(i, n, 1) PER(j, n, 1) {
        S[i][j] == '0' ? (f[i][j] = g[i + 1][j + 1] + 1) : (f[i][j] = 0);
        g[i][j] = std::max({g[i + 1][j], g[i][j + 1], f[i][j]});
    }
    if (g[1][1] >= K) return std::cout << "NO\n", 0;
    REP(x, 1, n) REP(y, 1, n) if (S[x][y] == '0') st[x].emplace(y);
    int pc = 0;
    PER(Rd, K - 1, 1) {
        int x = 1, y = n - Rd + 1; ++pc;
        if (S[x][y] == '0') st[x].erase(y);
        REP(tx, 1, n - Rd + 1) {
            while (true) {
                auto it = st[tx].upper_bound(y);
                if (it == st[tx].begin()) break;
                for (--it; y > *it || x < tx; ) {
                    vs[x][y] = 1;
                    if (y > *it && !vs[x][y - 1]) --y;
                    else if (x < tx && !vs[x + 1][y]) ++x;
                }
                st[tx].erase(it);
            }
        }
        while (y > 1 || x < n - Rd + 1) {
            vs[x][y] = 1;
            if (y > 1 && !vs[x][y - 1]) --y;
            else if (x < n - Rd + 1 && !vs[x + 1][y]) ++x;
        }
        vs[x][y] = 1;
    }
    std::cout << "YES\n";
    REP(i, 1, n) { REP(j, 1, n) std::cout << (vs[i][j] ? '1' : '0'); std::cout << '\n'; } 
    return 0;
}
void FlyWheel() {
    REP(i, 1, n) mset(f[i], 0, n + 1), mset(g[i], 0, n + 1), mset(vs[i], 0, n + 1), st[i].clear();
}
signed main() {
//  freopen("test.out", "w", stdout);
    std::ios::sync_with_stdio(false), std::cin.tie(0), std::cout.tie(0);
    int TEST = 0; std::cin >> TEST;
    while (TEST--) Create(), FlyWheel();
    return 0;
}