POJ--2749--2-SAT加二分判定

//二分答案,判断2-SAT合理性
#include
#include
#include
#include
#include
using namespace std;
const int N = 1e3 + 10;
int head[N], tot;
int n, a, b;
int dis1[N], dis2[N], d;
int hate[N][2], like[N][2];
int sccno[N], scc_cnt, dfn[N], low[N], idx;
stackst;
struct Point {
	int x, y;
}p[N], s1, s2;
struct Edge {
	int to;
	int nxt;
}e[N*N];
void add(int u, int v) {
	e[++tot].to = v;
	e[tot].nxt = head[u];
	head[u] = tot;
}
int getdis(Point p1, Point p2) {
	return abs(p1.x - p2.x) + abs(p1.y - p2.y);
}
void dfs(int u) {
	dfn[u] = low[u] = ++idx;
	st.push(u);
	for (int v, i = head[u]; i != -1; i = e[i].nxt) {
		v = e[i].to;
		if (!dfn[v]) {
			dfs(v);
			low[u] = min(low[u], low[v]);
		}
		else if (!sccno[v])
			low[u] = min(low[u], dfn[v]);
	}
	if (dfn[u] == low[u]) {
		scc_cnt++;
		while (1) {
			int x = st.top();
			st.pop();
			sccno[x] = scc_cnt;
			if (x == u)break;
		}
	}
}
void find_scc() {
	memset(sccno, 0, sizeof(sccno));
	memset(dfn, 0, sizeof(dfn));
	memset(low, 0, sizeof(low));
	scc_cnt = idx = 0;
	for (int i = 1; i <= 2 * n; i++)
		if (!dfn[i])dfs(i);
}
bool solve(int x) {
	memset(head, -1, sizeof(head));
	tot = 0;
	for (int i = 1; i <= n; i++) {
		for (int j = 1; j <= n; j++) {
			if (i == j)continue;
			if (dis1[i] + dis1[j] > x) {  //i,j不能同时连接s1: 若i连s1,j必连s2;若j连s1,i必连s2
				add(i, j + n);
				add(j, i + n);
			}
			if (dis2[i] + dis2[j] > x) {  //i,j不能同时连接s2: 若i连s2,j必连s1;若j连s2,i必连s1
				add(i + n, j);
				add(j + n, i);
			}
			if (dis1[i] + dis2[j] + d > x) {  //i连s1且j连s2的情况不成立: 若i连s1,j必连s1;若j连s2,i必连s2
				add(i, j);
				add(j + n, i + n);
			}
			if (dis2[i] + dis1[j] + d > x) {  //i连s2且j连s1的情况不成立: 若i连s2,j必连s2;若j连s1,i必连s1
				add(i + n, j + n);
				add(j, i);
			}
		}
	}
	for (int i = 1; i <= a; i++) {  //互相讨厌的对
		add(hate[i][0], hate[i][1] + n);
		add(hate[i][0] + n, hate[i][1]);
		add(hate[i][1], hate[i][0] + n);
		add(hate[i][1] + n, hate[i][0]);
	}
	for (int i = 1; i <= b; i++) {  //互相喜欢的对
		add(like[i][0], like[i][1]);
		add(like[i][0] + n, like[i][1] + n);
		add(like[i][1], like[i][0]);
		add(like[i][1] + n, like[i][0] + n);
	}
	find_scc();
	for (int i = 1; i <= n; i++)
		if (sccno[i] == sccno[i + n])return false;
	return true;
}
int main() {
	scanf("%d%d%d", &n, &a, &b);
	scanf("%d%d%d%d", &s1.x, &s1.y, &s2.x, &s2.y);
	d = getdis(s1, s2);
	int maxx = 0;
	for (int i = 1; i <= n; i++) {
		scanf("%d%d", &p[i].x, &p[i].y);
		dis1[i] = getdis(p[i], s1);
		dis2[i] = getdis(p[i], s2);
		maxx = max(maxx, max(dis1[i], dis2[i]));
	}
	for (int i = 1; i <= a; i++) scanf("%d%d", &hate[i][0], &hate[i][1]);
	for (int i = 1; i <= b; i++) scanf("%d%d", &like[i][0], &like[i][1]);
	int l = 0, r = 2 * maxx + d + 1;
	int ans = r;
	while (l <= r) {
		int mid = (l + r) / 2;
		if (solve(mid)) {
			ans = min(ans, mid);
			r = mid - 1;
		}
		else l = mid + 1;
	}
	if (ans == 2 * maxx + d + 1)ans = -1;
	printf("%d\n", ans);
	return 0;
}

你可能感兴趣的:(POJ--2749--2-SAT加二分判定)