码迷,mamicode.com
首页 > 其他好文 > 详细

POJ 3905 Perfect Election(2-sat)

时间:2014-10-27 01:46:37      阅读:183      评论:0      收藏:0      [点我收藏+]

标签:style   blog   http   color   io   os   ar   for   sp   

POJ 3905 Perfect Election

题目链接

思路:很裸的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;

int n, m;

int main() {
	while (~scanf("%d%d", &n, &m)) {
		gao.init(n);
		int u, v;
		while (m--) {
			scanf("%d%d", &u, &v);
			if (u > 0 && v > 0) {
				u--; v--;
				gao.add_Edge(u, 1, v, 1);
			} else if (u > 0 && v < 0) {
				v = -v;
				u--; v--;
				gao.add_Edge(u, 1, v, 0);
			} else if (u < 0 && v > 0) {
				u = -u;
				u--; v--;
				gao.add_Edge(u, 0, v, 1);
			} else if (u < 0 && v < 0) {
				u = -u; v = -v;
				u--; v--;
				gao.add_Edge(u, 0, v, 0);
			}
		}
		printf("%d\n", gao.solve());
	}
	return 0;
}


POJ 3905 Perfect Election(2-sat)

标签:style   blog   http   color   io   os   ar   for   sp   

原文地址:http://blog.csdn.net/accelerator_/article/details/40489523

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!