zoukankan      html  css  js  c++  java
  • 图论:2-SAT模板

     1 #include<cstdio>
     2 #include<vector>
     3 #include<cstring>
     4 using namespace std;
     5 
     6 const int maxn = _____;
     7 
     8 struct TwoSAT
     9 {
    10     int n;
    11     vector<int> G[maxn*2];
    12     bool mark[maxn*2];
    13     int S[maxn*2], c;
    14 
    15     bool dfs(int x)
    16     {
    17         if (mark[x^1]) return false;
    18         if (mark[x]) return true;
    19         mark[x] = true;
    20         S[c++] = x;
    21         for (int i = 0; i < G[x].size(); i++)
    22             if (!dfs(G[x][i])) return false;
    23         return true;
    24     }
    25 
    26     void init(int n) // 一定要注意初始化的点数,别弄错
    27     {
    28         this->n = n;
    29         for (int i = 0; i < n*2; i++) G[i].clear();
    30         memset(mark, 0, sizeof(mark));
    31     }
    32 
    33     // x = xval or y = yval
    34     void add_clause(int x, int xval, int y, int yval) // 编号从0~n-1
    35     {
    36         x = x * 2 + xval;
    37         y = y * 2 + yval;
    38         G[x^1].push_back(y);
    39         G[y^1].push_back(x);
    40     }
    41 
    42     bool solve()
    43     {
    44         for(int i = 0; i < n*2; i += 2)
    45             if(!mark[i] && !mark[i+1])
    46             {
    47                 c = 0;
    48                 if(!dfs(i))
    49                 {
    50                     while(c > 0) mark[S[--c]] = false;
    51                     if(!dfs(i+1)) return false;
    52                 }
    53             }
    54         return true;
    55     }
    56 };
    57 
    58 TwoSAT solver;
    59 ////////////////////////////////////////////////////
    60 //二分搜索,2-SAT中经常会用到
    61         int L=____,R=____;
    62         while(L < R)
    63         {
    64             int M = L + (R-L+1)/2;
    65             if(test(M)) L = M; // M满足条件的话test返回真
    66             else R = M-1;
    67         }
    68         printf("%d
    ",L);
  • 相关阅读:
    JavaScript单线程和浏览器事件循环简述
    Promise的前世今生和妙用技巧
    自定义Angular插件
    smartcrop.js智能图片裁剪库
    判断是否安装微博
    Java 注解
    android tools使用方式
    listview复用机制研究
    java 驼峰字符和下划线字符相互转换工具类
    剪切板(复制、粘贴)工具类
  • 原文地址:https://www.cnblogs.com/oneshot/p/4006463.html
Copyright © 2011-2022 走看看