Advertisement
RaFiN_

TWO SAT

Sep 12th, 2020
1,211
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.99 KB | None | 0 0
  1.  
  2. //TWO SAT
  3. ///Zero Indexed
  4. ///we have vars variables
  5. ///F=(x_0 XXX y_0) and (x_1 XXX y_1) and ... (x_{vars-1} XXX y_{vars-1})
  6. ///here {x_i,y_i} are variables
  7. ///and XXX belongs to {OR,XOR}
  8. ///is there any assignment of variables such that F=true
  9.  
  10. struct twosat {
  11.     int n;  /// total size combining +, -. must be even.
  12.     vector< vector<int> > g, gt;    /// graph, transpose graph
  13.     vector<bool> vis, res;  /// visited and resulting assignment
  14.     vector<int> comp;   /// component number
  15.     stack<int> ts;  /// topsort
  16.  
  17.     twosat(int vars=0) {
  18.         n = (vars << 1);
  19.         g.resize(n);
  20.         gt.resize(n);
  21.     }
  22.  
  23.     ///zero indexed, be careful
  24.  
  25.     ///if you want to force variable a to be true in OR or XOR combination
  26.     ///add addOR (a,1,a,1);
  27.     ///if you want to force variable a to be false int OR or XOR combination
  28.     ///add addOR (a,0,a,0);
  29.  
  30.     ///(x_a or (not x_b))-> af=1,bf=0
  31.     void addOR(int a, bool af, int b, bool bf) {
  32.         a += a+(af^1);
  33.         b += b+(bf^1);
  34.         g[a^1].push_back(b);    /// !a => b
  35.         g[b^1].push_back(a);    /// !b => a
  36.         gt[b].push_back(a^1);
  37.         gt[a].push_back(b^1);
  38.     }
  39.     ///(x_a or x_b)-> af=0,bf=0
  40.     void addXOR(int a,bool af,int b,bool bf)
  41.     {
  42.         addOR(a,af,b,bf);
  43.         addOR(a,!af,b,!bf);
  44.     }
  45.     ///add this type of condition->
  46.     ///add(a,af,b,bf) means if a is af then b must need to be bf
  47.     void add(int a,bool af,int b,bool bf)
  48.     {
  49.         a += a+(af^1);
  50.         b += b+(bf^1);
  51.         g[a].push_back(b);
  52.         gt[b].push_back(a);
  53.     }
  54.     void dfs1(int u) {
  55.         vis[u] = true;
  56.         for(int v : g[u]) if(!vis[v]) dfs1(v);
  57.         ts.push(u);
  58.     }
  59.  
  60.     void dfs2(int u, int c) {
  61.         comp[u] = c;
  62.         for(int v : gt[u]) if(comp[v] == -1) dfs2(v, c);
  63.     }
  64.     bool ok() {
  65.         vis.resize(n, false);
  66.         for(int i=0; i<n; ++i) if(!vis[i]) dfs1(i);
  67.  
  68.         int scc = 0;
  69.         comp.resize(n, -1);
  70.         while(!ts.empty()) {
  71.             int u = ts.top();
  72.             ts.pop();
  73.             if(comp[u] == -1) dfs2(u, scc++);
  74.         }
  75.  
  76.         res.resize(n/2);
  77.         for(int i=0; i<n; i+=2) {
  78.             if(comp[i] == comp[i+1]) return false;
  79.             res[i/2] = (comp[i] > comp[i+1]);
  80.         }
  81.         return true;
  82.     }
  83. };
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement