又是一道2-sat入门水题,5分钟轻松1A。前面博客已经介绍过2-sat,在此不再赘述,直接上代码。
#include<iostream>
#include<vector>
using namespace std;
#define maxn 2010
int n, m;
vector<int> mp[maxn];
int dfn[maxn], low[maxn];
bool instack[maxn];
int stap[maxn];
int belong[maxn];
int index, cnt, stop;
int min(int a, int b)
{
return a < b ? a : b;
}
void tarjan(int u)
{
dfn[u] = low[u] = index++;
instack[u] = true;
stap[++stop] = u;
for(int i = 0; i < mp[u].size(); i++)
{
int v = mp[u][i];
if(!dfn[v])
{
tarjan(v);
low[u] = min(low[u], low[v]);
}
else if(instack[v])
{
low[u] = min(low[u], dfn[v]);
}
}
if(low[u] == dfn[u])
{
cnt++;
int v;
do
{
v = stap[stop--];
instack[v] = false;
belong[v] = cnt;
}while(v != u);
}
}
int main()
{
int a, b, c, d;
while(~scanf("%d%d", &n, &m))
{
for(int i = 1; i <= 2*n; i++)
mp[i].clear();
for(int i = 1; i <= m; i++)
{
scanf("%d%d%d%d", &a, &b, &c, &d);
a++, b++;
// 图中2*n-1为妻子, 2*n为丈夫
// 输入中0为妻子, 1为丈夫
if(c && d) // 1 1
{
mp[2*a].push_back(2*b-1);
mp[2*b].push_back(2*a-1);
}
else if(c && !d) // 1 0
{
mp[2*a].push_back(2*b);
mp[2*b-1].push_back(2*a-1);
}
else if(!c && d) // 0 1
{
mp[2*a-1].push_back(2*b-1);
mp[2*b].push_back(2*a);
}
else if(!c && !d) // 0 0
{
mp[2*a-1].push_back(2*b);
mp[2*b-1].push_back(2*a);
}
}
index = stop = cnt = 0;
memset(belong, 0, sizeof(belong));
memset(instack, false, sizeof(instack));
memset(dfn, 0, sizeof(dfn));
memset(low, 0, sizeof(low));
int flag = 0;
for(int i = 1; i <= 2*n; i++)
{
if(!dfn[i])
tarjan(i);
}
for(int i = 1; i <= n; i++)
{
if(belong[2*i-1] == belong[2*i])
{
flag = 1;
break;
}
}
if(flag)
printf("NO\n");
else
printf("YES\n");
}
return 0;
}