2-SAT!!!

板子题卡了我一个点

Luogu P4782 【模板】2-SAT

#include <iostream>
#include <stack>
#include <queue>

using namespace std;
const int maxn = 2e6 + 10;
struct Edge
{
	int nxt, to;
}edges[maxn];

bool vis[maxn];
int tot;
int id;
int cols;
int in[maxn];
int col[maxn];
int dfn[maxn];
int low[maxn];
int head[maxn];
stack <int> stk;

inline void add(int u, int v)
{
	tot++;
	edges[tot].nxt = head[u];
	edges[tot].to = v;
	head[u] = tot;
}
void tar(int x)
{
	dfn[x] = low[x] = ++id;
	stk.push(x);
	vis[x] = true;
	for (int i = head[x]; i; i = edges[i].nxt)
	{
		int to = edges[i].to;
		if (!dfn[to])
		{
			tar(to);
			low[x] = min(low[x], low[to]);
		}
		else if (vis[to])
		{
			low[x] = min(low[x], dfn[to]);
		}
	}
	if (dfn[x] == low[x])
	{
		cols++;
		int y;
		do
		{
			y = stk.top();
			stk.pop();
			col[y] = cols;
			vis[y] = false;
		}while (x != y);
	}
}

int main()
{
	int n, m;
	cin >> n >> m;
	for (int i = 1; i <= m; ++i)
	{
		int x, a, y, b;
		cin >> x >> a >> y >> b;
		if (a == true && b == true)
		{
			add(x, y + n);
			add(y, x + n);
		}
		if (a == false && b == false)
		{
			add(x + n, y);
			add(y + n, x);
		}
		if (a == true && b == false)
		{
			add(x, y);
			add(y + n, x + n);
		}
		if (a == false && b == true)
		{
			add(x + n, y + n);
			add(y, x);
		}
	}
	for (int i = 1; i <= 2 * n; ++i)
	{
		if (!dfn[i])
			tar(i);
	}
	for (int i = 1; i <= n; ++i)
	{
		if (col[i] == col[i + n])
		{
			cout << "IMPOSSIBLE" << '\n';
			return 0;
		}
	}
	cout << "POSSIBLE" << '\n';
	for (int i = 1; i <= n; ++i)
	{
		if (col[i] > col[i + n])
		{
			cout << 1 << ' ';
		}
		else
		{
			cout << 0 << ' ';
		}
	}
	return 0;
}
posted @   xjh-OI-Forever  阅读(4)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 地球OL攻略 —— 某应届生求职总结
· 周边上新:园子的第一款马克杯温暖上架
· Open-Sora 2.0 重磅开源!
· 提示词工程——AI应用必不可少的技术
· .NET周刊【3月第1期 2025-03-02】
点击右上角即可分享
微信分享提示