80pts 并查集+二分 求调
查看原帖
80pts 并查集+二分 求调
374769
Epi4any楼主2022/11/5 23:13

TLE on test #2
WA on test #7

#include <iostream>
#include <cstring>
#include <cmath>
using namespace std;
using pii = pair<int, int>;
inline int read() {
	int 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 << 1) + (x << 3) + (ch ^ 48);
		ch = getchar();
	}
	return x * f;
}
const int maxn = 505;
int n, m, map[maxn][maxn], mx = 0, cnt = 0;
pii flag[maxn * maxn];
struct queryset {
	int fa[maxn * maxn], siz[maxn * maxn];
	int getf(int x) {
		if (fa[x] == x) return x;
		return getf(fa[x]);
	}
	void merge(int x, int y) {
		int fx = getf(x), fy = getf(y);
		if (fx == fy) return;
		if (siz[fy] > siz[fx]) fa[fx] = fy, siz[fy] += siz[fx];
		else fa[fy] = fx, siz[fx] += siz[fy];
	}
	void init() {
		for (int i = 1; i <= n * m; i++) fa[i] = i;
		memset(siz, 0, sizeof(siz));
	}
} s;
int get_hash(int x, int y) {
	return (x - 1) * m + y;
}
bool check(int d) {
	s.init();
	for (int i = 1; i <= n; i++) {
		for (int j = 1; j <= m; j++) {
			if (abs(map[i - 1][j] - map[i][j]) <= d) s.merge(get_hash(i, j), get_hash(i - 1, j));
			if (abs(map[i + 1][j] - map[i][j]) <= d) s.merge(get_hash(i, j), get_hash(i + 1, j));
			if (abs(map[i][j - 1] - map[i][j]) <= d) s.merge(get_hash(i, j), get_hash(i, j - 1));
			if (abs(map[i][j + 1] - map[i][j]) <= d) s.merge(get_hash(i, j), get_hash(i, j + 1));
		}
	}
	for (int i = 1; i < cnt; i++) {
		int fx = s.getf(get_hash(flag[i].first, flag[i].second));
		int fy = s.getf(get_hash(flag[i + 1].first, flag[i + 1].second));
		if (fx != fy) return false;
	}
	return true;
}
void Dic_acumulate() {
	int l = 0, r = mx;
	while (l < r) {
		int mid = (l + r) >> 1;
		if (check(mid)) r = mid;
		else l = mid + 1;
	}
	cout << l << endl;
}
int main() {
	n = read(), m = read();
	for (int i = 0; i <= n + 1; i++) map[0][i] = 2e9, map[i][0] = 2e9, map[n + 1][i] = 2e9, map[i][m + 1] = 2e9;
	for (int i = 1; i <= n; i++) for (int j = 1; j <= m; j++) {
			map[i][j] = read(), mx = max(mx, map[i][j]);
		}
	for (int i = 1; i <= n; i++) for (int j = 1, x; j <= m; j++) {
			x = read();
			if (x == 1) flag[++cnt].first = i, flag[cnt].second = j;
		}
	Dic_acumulate();
	return 0;
}

大佬轻喷qwq

2022/11/5 23:13
加载中...