2-sat模板
这篇博客写得非常好
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
//Achen
#include<algorithm>
#include<iostream>
#include<cstring>
#include<cstdlib>
#include<cstdio>
#include<vector>
#include<queue>
#include<ctime>
#include<cmath>
const int N=1007;
typedef long long LL;
using namespace std;
int T,n,m,bel[N],dfn[N],low[N];
template<typename T> void read(T &x) {
char ch=getchar(); x=0; T f=1;
while(ch!='-'&&(ch<'0'||ch>'9')) ch=getchar();
if(ch=='-') f=-1,ch=getchar();
for(;ch>='0'&&ch<='9';ch=getchar()) x=x*10+ch-'0'; x*=f;
}
int ecnt,fir[N],nxt[20007],to[20007];
void add(int u,int v) {
nxt[++ecnt]=fir[u]; fir[u]=ecnt; to[ecnt]=v;
}
int get() {
int x; char o=getchar();
while(o!='h'&&o!='m') o=getchar(); read(x);
return o=='h'?(x<<1):(x<<1|1);
}
int que[N],dfs_clock,top,tot;
void tarjan(int x) {
dfn[x]=low[x]=++dfs_clock;
que[++top]=x;
for(int i=fir[x];i;i=nxt[i]) {
if(!dfn[to[i]]) {
tarjan(to[i]);
low[x]=min(low[x],low[to[i]]);
}
else if(!bel[to[i]]) low[x]=min(low[x],dfn[to[i]]);
}
if(dfn[x]==low[x]) {
tot++;
while(top) {
int tp=que[top--];
bel[tp]=tot;
if(tp==x) break;
}
}
}
int main() {
#ifdef DEBUG
freopen(".in","r",stdin);
freopen(".out","w",stdout);
#endif
read(T);
while(T--) {
read(n); read(m); ecnt=0;
memset(dfn,0,sizeof(dfn));
memset(bel,0,sizeof(bel));
memset(fir,0,sizeof(fir));
for(int i=1;i<=m;i++) {
int x=get();
int y=get();
add(x^1,y); add(y^1,x);
}
dfs_clock=tot=0;
for(int i=2;i<=(n<<1|1);i++) if(!dfn[i]) tarjan(i);
int fl=0;
for(int i=2;i<=(n<<1|1);i+=2)
if(bel[i]==bel[i|1]) {
fl=1; break;
}
if(fl) puts("BAD");
else puts("GOOD");
}
return 0;
}