首页 > 代码库 > POJ 3207 Ikki's Story IV - Panda's Trick(2-sat)

POJ 3207 Ikki's Story IV - Panda's Trick(2-sat)

POJ 3207 Ikki‘s Story IV - Panda‘s Trick

题目链接

题意:一个圆上顺序n个点,然后有m组连线,连接两点,要求这两点可以往圆内或圆外,问是否能构造出使得满足所有线段不相交

思路:2-sat,判断相交的建边,一个在内,一个在外,然后跑一下2-sat即可

代码:

#include <cstdio>
#include <cstring>
#include <cstdlib>
#include <vector>
#include <algorithm>
using namespace std;

const int MAXNODE = 2005;

struct TwoSet {
	int n;
	vector<int> g[MAXNODE * 2];
	bool mark[MAXNODE * 2];
	int S[MAXNODE * 2], sn;

	void init(int tot) {
		n = tot * 2;
		for (int i = 0; i < n; i += 2) {
			g[i].clear();
			g[i^1].clear();
		}
		memset(mark, false, sizeof(mark));
	}

	void add_Edge(int u, int uval, int v, int vval) {
		u = u * 2 + uval;
		v = v * 2 + vval;
		g[u^1].push_back(v);
		g[v^1].push_back(u);
	}

	void delete_Edge(int u, int uval, int v, int vval) {
		u = u * 2 + uval;
		v = v * 2 + vval;
		g[u^1].pop_back();
		g[v^1].pop_back();
	}

	bool dfs(int u) {
		if (mark[u^1]) return false;
		if (mark[u]) return true;
		mark[u] = true;
		S[sn++] = u;
		for (int i = 0; i < g[u].size(); i++) {
			int v = g[u][i];
			if (!dfs(v)) return false;
		}
		return true;
	}

	bool solve() {
		for (int i = 0; i < n; i += 2) {
			if (!mark[i] && !mark[i + 1]) {
				sn = 0;
				if (!dfs(i)){
					for (int j = 0; j < sn; j++)
						mark[S[j]] = false;
					sn = 0;
					if (!dfs(i + 1)) return false;
				}
			}
		}
		return true;
	}
} gao;

const int N = 505;

int n, m, l[N], r[N];

int main() {
	while (~scanf("%d%d", &n, &m)) {
		gao.init(m);
		for (int i = 0; i < m; i++) {
			scanf("%d%d", &l[i], &r[i]);
			if (l[i] > r[i]) swap(l[i], r[i]);
			for (int j = 0; j < i; j++) {
				if ((l[i] > l[j] && l[i] < r[j] && r[j] > l[i] && r[j] < r[i]) || (r[i] > l[j] && r[i] < r[j] && l[j] > l[i] && r[j] < r[i])) { 
					gao.add_Edge(i, 0, j, 0);
					gao.add_Edge(i, 1, j, 1);
				}
			}
		}
		printf("%s\n", gao.solve() ? "panda is telling the truth..." : "the evil panda is lying again");
	}
	return 0;
}


POJ 3207 Ikki's Story IV - Panda's Trick(2-sat)