Problem 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
Output
如果存在一种情况 则输出YES
否则输出 NO
Sample Input
2
1
0 1 1 1
Sample Output
YES
思路
经典的2-sat问题,一道入门题。按照冲突条件建立边,如果A1C1 和 A2C1冲突:
- 那么A1C1只能和A2C2同时出建立A1C1 -> A2C2的一条有向边。选A1C1只能选A2C2。
- 或者A2C1和A1C2同时出席。建立A2C1 -> A1C2的一条有向边。选A2C1只能选A1C2。
注意依赖关系,谁依赖谁。建图完成之后直接做Tarjan + scc。最后判断有没有一对夫妻同时出席(属于同一个强连通分量),如果存在就不符合条件,否则就是可行的。
#include <iostream>
#include <cstring>
#include <algorithm>
#include <stack>
#include <cstdio>
using namespace std;
const int maxn = 3005;
struct edge{
int to;
int next;
}e[maxn*maxn];
int head[maxn];
int dfn[maxn];
int low[maxn];
int scc[maxn];
stack<int>s;
int tot,cnt,res;
void clear_set()
{
tot = cnt = res = 0;
memset(head,-1,sizeof(head));
memset(dfn,0,sizeof(dfn));
memset(low,0,sizeof(low));
memset(scc,0,sizeof(scc));
while(!s.empty()) s.pop();
}
void addedge(int x,int y)
{
e[tot].to = y;
e[tot].next = head[x];
head[x] = tot++;
}
void tarjan(int x)
{
dfn[x] = low[x] = ++cnt;
s.push(x);
for(int i = head[x];~i;i = e[i].next){
int y = e[i].to;
if(!dfn[y]){
tarjan(y);
low[x] = min(low[x],low[y]);
}
else if(!scc[y]){
low[x] = min(low[x],dfn[y]);
}
}
if(low[x] == dfn[x]){
res++;
while(true){
int t = s.top();
s.pop();
scc[t] = res;
if(t == x) break;
}
}
}
int main()
{
int n,m;
while(~scanf("%d",&n)){
scanf("%d",&m);
clear_set();
for(int i = 0;i < m;i++){
int a,b,x,y;
scanf("%d%d%d%d",&a,&b,&x,&y);
a = 2*a + x; b = 2*b + y;
addedge(a,b^1); addedge(b,a^1);
// ax by有矛盾
}
for(int i = 0;i < 2*n;i++){
if(!dfn[i]){
tarjan(i);
}
}
bool f = true;
for(int i = 0;i < n;i++){
if(scc[i*2] == scc[i*2+1]){
f = false;
break;
}
}
if(f){
puts("YES");
}
else{
puts("NO");
}
}
return 0;
}
愿你走出半生,归来仍是少年~