https://www.luogu.org/problemnew/solution/P4782

这里的大佬已经说的够好了

洛谷P-4782   2-sat+Tarjan-LMLPHP

#include<iostream>
#include<cstring>
#include<cstdio>
#include<algorithm>
#include<vector>
#include<stack>
#define maxn 2002010
using namespace std;
vector<int>G[maxn];
stack<int>s;
void insert(int be, int en) {
G[be].push_back(en);
}
int low[maxn], dfn[maxn], df, ans, clor[maxn];
int tarjan(int x) {
//cout << x << endl;
low[x] = dfn[x] = ++df;
s.push(x);
for (int i = 0; i < G[x].size(); i++) {
int p = G[x][i]; if (!dfn[p]) {
tarjan(p);
low[x] = min(low[x], low[p]);
}
else if (!clor[p]) {
low[x] = min(low[x], dfn[p]);
}
}
if (low[x] == dfn[x]) {
ans++;
while (1) {
int a = s.top();
s.pop();
clor[a] = ans;
if (a == x) break;
}
}
return 0;
}
int n, m; int main() {
int n, m;
scanf("%d %d", &n, &m);
int be, en, a, b;
for (int i = 0; i < m; i++) {
scanf("%d %d %d %d", &be, &a, &en, &b);
insert(be + a * n, en + (b ^ 1)*n);
insert(en + b * n, be + (a ^ 1)*n);
}
for (int i = 1; i <= 2*n; i++) {
if (!dfn[i]) tarjan(i);
}
for (int i = 1; i <= n; i++) {
if (clor[i] == clor[i + n]) {
//cout << clor[i] << " " << clor[i + n] << endl;
printf("IMPOSSIBLE\n");
return 0;
}
}
printf("POSSIBLE\n");
for (int i = 1; i <= n; i++) {
printf("%d ", clor[i] > clor[i + n]);
}
printf("\n");
return 0;
}

  

05-26 06:33