图论(2-sat):HDU 3062 Party

Party

Time Limit: 2000/1000 MS (Java/Others)    Memory Limit: 32768/32768 K (Java/Others)
Total Submission(s): 5558    Accepted Submission(s): 1809


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
  模板题。
 1 #include <iostream>
 2 #include <cstring>
 3 #include <cstdio>
 4 using namespace std;
 5 const int maxn=5010;
 6 int n,m;
 7 int cnt,fir[maxn],nxt[maxn*600],to[maxn*600];
 8 void addedge(int a,int b){
 9     nxt[++cnt]=fir[a];
10     fir[a]=cnt;
11     to[cnt]=b;
12 }
13 int scc[maxn],scnt;
14 int ID[maxn],low[maxn],tot;
15 int st[maxn],top;
16 
17 void Tarjan(int x){
18     ID[x]=low[x]=++tot;st[++top]=x;
19     for(int i=fir[x];i;i=nxt[i]){
20         if(ID[to[i]]){
21             if(!scc[to[i]])
22                 low[x]=min(low[x],ID[to[i]]);
23         }
24         else{
25             Tarjan(to[i]);
26             low[x]=min(low[x],low[to[i]]);
27         }
28     }
29     if(low[x]==ID[x]){
30         ++scnt;
31         while(true){
32             int y=st[top--];
33             scc[y]=scnt;
34             if(x==y)break;
35         }
36     }    
37 }
38 bool Solve(){
39     for(int i=0;i<2*n;i++)
40         if(!ID[i])Tarjan(i);
41 
42     for(int i=0;i<n;i++)
43         if(scc[i*2]==scc[i*2+1])
44             return false;
45     return true;        
46 }
47 
48 void Init(){
49     memset(fir,0,sizeof(fir));
50     memset(scc,0,sizeof(scc));
51     memset(ID,0,sizeof(ID));
52     cnt=0;tot=0;scnt=0;
53 }
54 
55 int main(){
56     while(scanf("%d%d",&n,&m)!=EOF){
57         Init();
58         while(m--){
59             int a,b,c,d;
60             scanf("%d%d%d%d",&a,&b,&c,&d);
61             a=a*2+c;b=b*2+d;
62             addedge(a,b^1);addedge(b,a^1);
63         }
64         if(Solve())
65             printf("YES
");
66         else 
67             printf("NO
");    
68     }
69     return 0;    
70 }
原文地址:https://www.cnblogs.com/TenderRun/p/5631317.html