2-SAT【模板】

P4782 【模板】2-SAT

#include <bits/stdc++.h>
using namespace std;


inline long long read() {
	char ch = getchar();
	long long f = 1,x = 0;
	while (ch > '9' || ch < '0') { if (ch == '-')f = -1; ch = getchar(); }
	while (ch >= '0' && ch <= '9') { x = (x << 1) + (x << 3) + ch - '0'; ch = getchar(); }
	return x * f;
}
//void ReadFile() {
//	FILE* stream1;
//	freopen_s(&stream1,"in.txt", "r", stdin);
//	freopen_s(&stream1,"out.txt", "w", stdout);
//}

static auto speedup = []() {ios::sync_with_stdio(false); cin.tie(nullptr); cout.tie(nullptr); return nullptr; }();

const int maxn = 4e6 + 7;
int n,m,dfn[maxn],low[maxn],nTime = 0,color[maxn],c = 0,vis[maxn],st[maxn],stop = 0;

vector<int> e[maxn];

void tarjan(int x) {
	dfn[x] = low[x] = ++nTime;
	vis[x] = 1;
	st[++stop] = x;

	for (auto& y : e[x]) {
		if (!dfn[y]) {
			tarjan(y);
			low[x] = min(low[x], low[y]);
		}
		else if (vis[y]) low[x] = min(low[x], dfn[y]);
	}

	if (dfn[x] == low[x]) {
		c++;
		int v;
		do {
			v = st[stop--];
			color[v] = c;
			vis[v] = 0;
		} while (v != x);
	}
}
void add(int a, int b) {
	e[a].push_back(b);
}
void slove() {
	cin >> n >> m;
	int a, va, b, vb;
	for (int i = 1; i <= m; i++) {
		cin >> a >> va >> b >> vb;
		if (va && vb) {	
			//a v b == -a -> b ,-b -> a
			//e[a + n].push_back(b);
			//e[b + n].push_back(a);
			add(a, b + n);     //a=0则b=1 
			add(b, a + n);     //b=0则a=1 
		}
		else if (va && !vb) {
			// a v -b == -a -> -b, b->a
			//e[a + n].push_back(b + n);
			//e[b].push_back(a);
			add(a, b);       //a=0则b=0 
			add(b + n, a + n);   //b=1则a=1 
		}
		else if (!va && vb) {
			//-a v b == a -> b, -b -> -a
			//e[a].push_back(b);
			//e[b + n].push_back(a + n);
			add(a + n, b + n);   //a=1则b=1 
			add(b, a);       //b=0则a=0 
		}
		else if (!va && !vb) {
			//-a v -b == a -> -b, b -> -a
			//e[a].push_back(b + n);
			//e[b].push_back(a + n);
			add(a + n, b);     //a=1则b=0 
			add(b + n, a);     //b=1则a=0 
		}
	}
	int len = n << 1;
	for (int i = 1; i <= len; i++) {
		if (!dfn[i])tarjan(i);
	}

	for (int i = 1; i <= n; i++) {
		if (color[i] == color[i + n]) {
			printf("IMPOSSIBLE\n");
			return;
		}
	}
	printf("POSSIBLE\n");
	for (int i = 1; i <= n; i++) {
		printf("%d ", color[i] > color[i + n]);
	}
	printf("\n");
}
int main() {
	slove();
	return 0;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值