题解:AT_agc039_b [AGC039B] Graph Partition

· · 题解

其它题解在讲什么东西啊?

Solution

首先如果存在解,令 V'_1=V_1\cup V_3\cup V_5\cup\cdots,V'_2=V_2\cup V_4\cup V_6\cup\cdots 同样是一组解。而 k=2 即为二分图染色,因此有解的充要条件是原图是二分图。

设 c_i 为 i 所属集合,原题条件即为对于所有边 (x,y) 有 \lvert c_x-c_y\rvert=1。放宽限制,改为 \lvert c_x-c_y\rvert\le 1,容易差分约束跑出一组最大解。由于是二分图,根据最短路的性质不存在 c_x=c_y,因此满足原条件。

由于最短路差分约束跑出的解每个 c_i 都取到了上界,可以最大化 k。

复杂度瓶颈是最短路,复杂度为 \mathcal O(n^3)。

Code

#include <bits/stdc++.h>
#define REP(i, l, r) for (int i = (l); i <= (r); ++ i)
#define DEP(i, r, l) for (int i = (r); i >= (l); -- i)
#define fi first
#define se second
#define pb emplace_back
#define mems(x, v) memset((x), (v), sizeof(x))
#define SZ(x) (int)(x).size()
#define ALL(x) (x).begin(), (x).end()
#define ppc(x) __builtin_popcount(x)
using namespace std;
namespace Milkcat {
    typedef long long LL;
    typedef pair<LL, LL> pii;
    const int N = 205;
    int n, rs, c[N], f[N][N]; char a[N][N];
    void color(int x) {
        REP(y, 1, n) {
            if (a[x][y] == '0') continue;
            if (c[y] < 0) c[y] = !c[x], color(y);
            else if (c[x] == c[y]) rs = -2;
        }
    }
    int main() {
        cin >> n;
        REP(i, 1, n) REP(j, 1, n)
            cin >> a[i][j], f[i][j] = (a[i][j] == '1' ? 1 : 1e9);
        REP(k, 1, n) REP(i, 1, n) REP(j, 1, n)
            f[i][j] = min(f[i][j], f[i][k] + f[k][j]);
        REP(i, 1, n) REP(j, i + 1, n)
            if (f[i][j] < 1e9) rs = max(rs, f[i][j]);
        REP(i, 1, n) c[i] = -1;
        REP(i, 1, n)
            if (c[i] < 0) c[i] = 0, color(i);
        cout << rs + 1 << '\n';
        return 0;
    }
}
int main() {
    cin.tie(0)->sync_with_stdio(0);
    int T = 1;
    while (T --) Milkcat::main();
    return 0;
}