zoukankan      html  css  js  c++  java
  • hdu 3062 2-sat入门题

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

    #include <cstdio>
    #include <cmath>
    #include <algorithm>
    #include <iostream>
    #include <cstring>
    #include <queue>
    #include <vector>
    
    #define maxn 1250
    #define INF  0x3f3f3f
    using namespace std;
    
    struct TwoSat{
        int n;
        vector<int> G[maxn*2];
        bool mark[maxn*2];
        int s[maxn*2],cnt; 
        
        void init(int n){
            this->n = n;
            memset(mark,0,sizeof(mark));
            for(int i=0;i<n*2;i++) G[i].clear();
        }
        bool dfs(int u){
            if(mark[u^1]) return false;
            if(mark[u])   return true;
            mark[u] = true;
            s[cnt++] = u;
            for(int i=0;i<G[u].size();i++){
                if(!dfs(G[u][i]))  return false;
            }
            return true;
        }
        
        void add_clause(int u,int uval,int v,int vval){ //这儿有问题 
            u = u*2 + uval;    //u,v有矛盾; 
            v = v*2 + vval;
            G[u].push_back(v^1);
            G[v].push_back(u^1);
        }
        
        bool solve(){
            for(int i=0;i<n*2;i+=2){
                if(!mark[i] && !mark[i+1]){  //为啥这个地方不回溯; 
                    cnt = 0;
                    if(!dfs(i)){
                        while(cnt > 0) mark[s[--cnt]]  = false;  
                        if(!dfs(i+1)) return false;
                    } 
                }
            }
            return true;
        }
    }solver;
    
    int main()
    {
        //freopen("input.txt","r",stdin);    
        int n,m;
        while(scanf("%d%d",&n,&m)==2){
            solver.init(n);
            for(int i=1;i<=m;i++){
                int a,b,c,d;
                scanf("%d%d%d%d",&a,&b,&c,&d);
                solver.add_clause(a,c,b,d);
            }
            if(solver.solve())  printf("YES
    ");
            else                printf("NO
    ");
        }
    } 
    View Code
  • 相关阅读:
    模块的初始
    requests模块的高级用法
    爬虫数据解析方式
    2th
    0
    ..
    .

    1th-绪论
    Py2x & Py3x版本的区别
  • 原文地址:https://www.cnblogs.com/acmdeweilai/p/3235871.html
Copyright © 2011-2022 走看看