Description
有n对夫妻被邀请参加一个聚会,因为场地的问题,每对夫妻中只有1人可以列席。在2n 个人中,某些人之间有着很大的矛盾(当然夫妻之间是没有矛盾的),有矛盾的2个人是不会同时出现在聚会上的。有没有可能会有n 个人同时列席?
Input
n: 表示有n对夫妻被邀请 (n<= 1000)
m: 表示有m 对矛盾关系 ( m < (n - 1) * (n -1))
在接下来的m行中,每行会有4个数字,分别是 A1,A2,C1,C2
A1,A2分别表示是夫妻的编号
C1,C2 表示是妻子还是丈夫 ,0表示妻子 ,1是丈夫
夫妻编号从 0 到 n -1
m: 表示有m 对矛盾关系 ( m < (n - 1) * (n -1))
在接下来的m行中,每行会有4个数字,分别是 A1,A2,C1,C2
A1,A2分别表示是夫妻的编号
C1,C2 表示是妻子还是丈夫 ,0表示妻子 ,1是丈夫
夫妻编号从 0 到 n -1
Output
如果存在一种情况 则输出YES
否则输出 NO
否则输出 NO
2-sat问题的简单类型,可知其中的连接只会是a->b^1 和b-> a^1 因此可以不必建图找强连通分量即可。
依然用tarjan算法(dfs? 唔) 每次搜索当前染色状态是否合法,不合法回退即可
#include<cstdio>
#include<cstring>
#include<algorithm>
#include<cmath>
#include<iostream>
#include<vector>
#include<string>
#include<stack>
using namespace std;
const int N=1005;
typedef long long ll;
vector<int> mp[N*2];
int index,ans;
int sav[N*2],t;
bool mark[N*2];
//stack<int> stk;
int n,m;
inline void init()
{
/* index=0;
ans=0;
for(int i=1; i<=N; i++)
mp[i].clear();
memset(dfn,0,sizeof(dfn));
memset(low,0,sizeof(low));
memset(vis,0,sizeof(vis));
while(!stk.empty()) stk.pop();*/
}
bool dfs(int pos)
{
if(mark[pos^1]) return false;
if(mark[pos]) return true;
mark[pos]=1;
sav[t++]=pos; //作为tarjan中的栈使用
for(int i=0;i<mp[pos].size();i++)
{
int x=mp[pos][i];
if(!dfs(x)) return false;
}
return true;
}
bool solve()
{
for(int i=0; i<n*2; i+=2)
{
if(!mark[i]&&!mark[i^1])
{
t=0;
if(!dfs(i))
{
while(t>0) mark[sav[--t]]=0;
if (!dfs(i^1))
return false;
}
}
}
return true;
}
int main()
{
int x,y,a,b;
int T;
while(scanf("%d %d",&n,&m)!=EOF)
{
memset(mark,0,sizeof(mark));
for(int i=0; i<=n*2; i++)
mp[i].clear();
for(int i=0; i<m; i++)
{
scanf("%d %d %d %d",&x,&y,&a,&b);
if(a==0) x*=2;
else x=x*2+1;
if(b==0) y*=2;
else y=y*2+1;
mp[x].push_back(y^1);
mp[y].push_back(x^1);
}
printf("%s\n",solve()?"YES":"NO");
}
return 0;
}