HDU1814 Peaceful Commission 2SAT

http://acm.hdu.edu.cn/showproblem.php?pid=1814

输出最小字典序。

 1 #include<bits/stdc++.h> 
 2 const int MAXN = 20020; 
 3 const int MAXM = 100010;
 4 using namespace std; 
 5 struct Edge {
 6      int to,next; 
 7 }edge[MAXM]; 
 8 int head[MAXN],tot; 
 9 void init(){ 
10     tot = 0;    
11     memset(head,-1,sizeof(head)); 
12 }  
13 void addedge(int u,int v){
14     edge[tot].to = v;
15     edge[tot].next = head[u];
16     head[u] = tot++; 
17 } bool vis[MAXN];//è&#190;é&#171;±ê&#188;&#199;£&#172;&#206;atrue±íê&#190;&#209;&#161;&#212;&#241; 
18 int S[MAXN],top;//&#213;&#187; 
19 bool dfs(int u){
20     if(vis[u^1])return false;
21     if(vis[u])return true;     
22     vis[u] = true;     
23     S[top++] = u;     
24     for(int i = head[u];i != -1;i = edge[i].next)
25         if(!dfs(edge[i].to))    
26             return false;    
27     return true; 
28 }
29 bool Twosat(int n){ 
30     memset(vis,false,sizeof(vis));   
31     for(int i = 0;i < n;i += 2){        
32          if(vis[i] || vis[i^1])
33             continue;        
34         top = 0;  
35         if(!dfs(i)){       
36             while(top)
37                 vis[S[--top]] = false;   
38             if(!dfs(i^1)) return false;         
39         }     
40     }     
41     return true; 
42 } 
43 int main(){     
44     int n,m;   
45     int u,v;   
46     while(scanf("%d%d",&n,&m) == 2){ 
47         init();  
48            while(m--){      
49             scanf("%d%d",&u,&v);         
50             u--;v--;      
51             addedge(u,v^1);  
52             addedge(v,u^1);         
53         }      
54         if(Twosat(2*n)){  
55             for(int i = 0;i < 2*n;i++) 
56                 if(vis[i]) 
57                    printf("%d
",i+1);       
58         }  
59         else printf("NIE
");     
60     }    
61     return 0; 
62 } 
原文地址:https://www.cnblogs.com/poler/p/7367547.html