HDU 3062 Party (2-SAT)

题目链接:http://acm.hdu.edu.cn/showproblem.php?pid=3062

题意:中文题目,题意就不太用说了。

思路:根据公式┓(a∧b) = ┓a ∨ ┓b 将与关系转化为非关系,然后套用2-SAT模板即可。


#include<cstdio>
#include<cstring>
#include<string>
#include<cctype>
#include<iostream>
#include<set>
#include<map>
#include<cmath>
#include<sstream>
#include<vector>
#include<stack>
#include<queue>
#include<bitset>
#include<algorithm>
#define fin(a) freopen("a.txt","r",stdin)
#define fout(a) freopen("a.txt","w",stdout)
using namespace std;
const int maxn = 1000 + 10;

struct TwoSAT {
  int n;
  vector<int> G[maxn*2];
  bool mark[maxn*2];
  int S[maxn*2], c;

  bool dfs(int x) {
    if(mark[x^1]) return false;
    if(mark[x]) return true;
    mark[x] = true;
    S[c++] = x;
    for(int i = 0; i < G[x].size(); i++) {
      int v = G[x][i];
      if(!dfs(v)) return false;
    }
    return true;
  }

  void init(int n) {
    this->n = n;
    for(int i = 0; i < n*2; i++) G[i].clear();
    memset(mark, 0, sizeof mark);
  }

  void add_clause(int x, int xval, int y, int yval) {
    x = x * 2 + xval;
    y = y * 2 + yval;
    G[x^1].push_back(y);
    G[y^1].push_back(x);
  }

  bool solve() {
    for(int i = 0; i < n*2; i += 2) {
      if(!mark[i] && !mark[i+1]) {
        c = 0;
        if(!dfs(i)) {
          while(c > 0) mark[S[--c]] = false;
          if(!dfs(i+1)) return false;
        }
      }
    }
    return true;
  }

}twosat;

int main() {
  int n, m;
  while(scanf("%d%d", &n, &m) == 2) {
    twosat.init(n);
    while(m--) {
      int a1, a2, c1, c2;
      scanf("%d%d%d%d", &a1, &a2, &c1, &c2);
      twosat.add_clause(a1, !c1, a2, !c2);
    }
    if(twosat.solve()) printf("YES\n");
    else printf("NO\n");
  }
  return 0;
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值