跳到正文

题解

题解:AT_agc039_b [AGC039B] Graph Partition

喵仔牛奶约 3 分钟
原文
文章信息与版本

文章信息

发布
2025年6月16日
收录
2026年10月14日
更新
2026年11月14日
篇幅
约 3 分钟
获赞
5

版本

  1. v1当前

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

Solution

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

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

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

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

Code

C++
#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;
}
原文