P4782 【模板】2-SAT

简记:
1.参考学习:
https://blog.csdn.net/qaqwqaqwq/article/details/126124806
https://www.cnblogs.com/cjjsb/p/9771868.html
2.代码:

#include<iostream>
#include<vector>
#include<algorithm>
#include<math.h>
#include<sstream>
#include<string>
#include<string.h>
#include<iomanip>
#include<stdlib.h>
#include<map>
#include<queue>
#include<cmath>
#include<limits.h>
#include<climits>
#include<fstream>
#include<set>
#include<stack>
typedef long long ll;
using namespace std;
const int N = 2e6 + 20;
ll dfn, low[N], num[N];
ll  cnt,sccno[N];
stack<int>stk;
vector<int>G[N<<1];
void dfs(int u)
{
	low[u] = num[u] = ++dfn;
	stk.push(u);
	for (int i = 0; i < G[u].size(); i++)
	{
		int v = G[u][i];
		if (!num[v])
		{
			dfs(v);
			low[u] = min(low[u], low[v]);

		}
		else if (!sccno[v])low[u] = min(low[u], num[v]);
	}
	if (low[u] == num[u])
	{
		cnt++;
		while (1)
		{
			int v = stk.top();
			stk.pop();
			sccno[v] = cnt;
			if (u == v)break;
		}
	}
}
void tarjan(int n)
{
	dfn = cnt =0;
	memset(low, 0, sizeof(low));
	memset(num, 0, sizeof(num));
	for (int i = 1; i <= 2 * n; i++)
		if (!num[i])
			dfs(i);
}
bool tSAT(int n)
{
	tarjan(n);
	for (int i = 1; i <= n; i++)
		if (sccno[i] == sccno[i + n])
			return false;
	return true;
}
int main()
{
	ios::sync_with_stdio(false);
	cin.tie(0), cout.tie(0);
	int n, m; cin >> n >> m;
	for (int i = 0; i < m; i++)
	{
		int a, b, va, vb; 
		cin >> a >> va >> b >> vb;
		int nota = !va, notb = !vb;
		G[a + nota * n].push_back(b + vb * n);
		G[b + notb * n].push_back(a + va * n);
	}
	if (tSAT(n))
	{
		cout << "POSSIBLE" << '\n';
		for (int i = 1; i <= n; i++)
		{
			int ax = sccno[i] > sccno[i + n];
			cout << ax << ' ';
		}
	}
	else cout << "IMPOSSIBLE";
	return 0;
}

记录下手滑的乐子时刻()

posted on 2024-05-11 14:49  WHUStar  阅读(5)  评论(0编辑  收藏  举报