2SAT.cpp 786 B

1234567891011121314151617181920212223242526272829303132333435363738
  1. struct TwoSAT {
  2. int n;
  3. VI G[maxn*2];
  4. bool mark[maxn*2];
  5. int S[maxn*2], c;
  6. bool dfs(int x) {
  7. if (mark[x^1]) return false;
  8. if (mark[x]) return true;
  9. mark[x] = true;
  10. S[c++] = x;
  11. for (int i = 0 ; i < G[x].size(); i++)
  12. if (!dfs(G[x][i])) return false;
  13. return true;
  14. }
  15. void init(int n) {
  16. this->n = n;
  17. for (int i = 0; i < n*2; i++) G[i].clear();
  18. memset(mark, 0, sizeof(mark));
  19. }
  20. //x =xval or y = yval
  21. void add_clause(int x, int xval, int y ,int yval) {
  22. x = x * 2 + xval;
  23. y = y * 2 + yval;
  24. G[x^1].push_back(y);
  25. G[y^1].push_back(x);
  26. }
  27. bool solve() {
  28. for (int i = 0; i < n * 2; i += 2)
  29. if (!mark[i] && !mark[i+1]){
  30. c = 0;
  31. if (!dfs(i)){
  32. while (c > 0) mark[S[--c]] = false;
  33. if (!dfs(i+1)) return false;
  34. }
  35. }
  36. return true;
  37. }
  38. };