2-SAT模板

来源:互联网 发布:天津mac口红专柜 编辑:程序博客网 时间:2024/05/29 02:01
</pre><pre name="code" class="cpp">/*==============================================*\  方法一:即为大白书上的描述\*==============================================*/const int maxn = 8005; //maxn为多少对const int maxm = 20005; //maxm为m的最大值int n,m; //n对夫妻,m对互斥关系 struct EdgeNode  {      int to;      int next;  };  struct TwoSAT{    int head[maxn*2];    EdgeNode edges[maxm*2];    int edge,n;    bool mark[maxn*2];    int S[maxn*2],c;    void init(int n)    {        this->n=n;        memset(mark,0,sizeof(mark));        memset(head,-1,sizeof(head));        edge=0;    }    void addedge(int u,int v)    {        edges[edge].to=v,edges[edge].next=head[u],head[u]=edge++;    }    // x = xval or y = yval    void add_clause(int x,int xval,int y,int yval)    {        x=x*2+xval;        y=y*2+yval;        addedge(x^1,y);  //x^1可以推出y就建立一条对应的边,下同        addedge(y^1,x);    }    // x = xval    void add_con(int x,int xval)    {        x=x*2+xval;        addedge(x^1,x);    }    bool dfs(int x)    {        if (mark[x^1]) return false; //节点已被访问,下同        if (mark[x]) return true;        mark[x]=true;  //标记xi        S[c++]=x;        for (int i=head[x]; i!=-1; i=edges[i].next) //邻接边搜索            if (!dfs(edges[i].to)) return false;        return true;    }    bool solve()    {        for (int i=0; i<n*2; i+=2)            if (!mark[i]&&!mark[i+1])            {                c=0;                if (!dfs(i))//如果标记xi为假不成立,则从头标记xi为真                {                    while (c>0) mark[S[--c]]=false;//返回假设的起点                    if (!dfs(i+1)) return false;//判断是否成立                }            }        return true;    }};/*==============================================*\   方法二:利用连通性,xi和xj不能再一个强连通分量里面\*==============================================*///=============================================================//2-sat模板const int maxn=2005; //maxn为n*2 int n,m; //n对夫妻,m对互斥关系 struct note{    int to;    int next;}edge[maxn*2*maxn];int head[maxn];int ip;int dfn[maxn],low[maxn],sccno[maxn],cnt,scc,instack[maxn];stack<int>stk;void init(){    memset(head,-1,sizeof(head));    ip=0;}void addedge(int u,int v){    edge[ip].to=v,edge[ip].next=head[u],head[u]=ip++;}// x,y为夫妻编号。 xval,yval表示夫或者妻 void add_cluse(int x,int xval,int y,int yval){    x=x*2+xval;    y=y*2+yval;    addedge(x,y^1);    addedge(y,x^1);}void dfs(int u){    dfn[u]=low[u]=++scc;    stk.push(u);    instack[u]=1;    for (int i=head[u]; i!=-1; i=edge[i].next)    {        int v=edge[i].to;        if (!dfn[v])        {            dfs(v);            low[u]=min(low[u],low[v]);        }        else if (instack[v])            low[u]=min(low[u],dfn[v]);    }    if (low[u]==dfn[u])    {        cnt++;        int x;        do        {            x=stk.top();            stk.pop();            sccno[x]=cnt;            instack[x]=0;        }while (x!=u);    }}bool solve(){    scc=cnt=0;    memset(sccno,0,sizeof(sccno));    memset(dfn,0,sizeof(dfn));    memset(low,0,sizeof(low));    memset(instack,0,sizeof(instack));    while (!stk.empty()) stk.pop();    for (int i=0; i<2*n; i++) if (!dfn[i]) dfs(i);    for (int i=0; i<2*n; i+=2)    {        if (sccno[i]==sccno[i^1]) return false;    }    return true;}//solve返回true证明2-sat有解,否则没解//============================================================

2-SAT求最小字典序模板—————————————————
题目:The Public Peace Commission should be legislated in Parliament of The Democratic Republic of Byteland according to The Very Important Law. Unfortunately one of the obstacles is the fact that some deputies do not get on with some others.

The Commission has to fulfill the following conditions:
1.Each party has exactly one representative in the Commission,
2.If two deputies do not like each other, they cannot both belong to the Commission.

Each party has exactly two deputies in the Parliament. All of them are numbered from 1 to 2n. Deputies with numbers 2i-1 and 2i belong to the i-th party .

Task
Write a program, which:
1.reads from the text file SPO.IN the number of parties and the pairs of deputies that are not on friendly terms,
2.decides whether it is possible to establish the Commission, and if so, proposes the list of members,
3.writes the result in the text file SPO.OUT.
Input
In the first line of the text file SPO.IN there are two non-negative integers n and m. They denote respectively: the number of parties, 1 <= n <= 8000, and the number of pairs of deputies, who do not like each other, 0 <= m <=2 0000. In each of the following m lines there is written one pair of integers a and b, 1 <= a < b <= 2n, separated by a single space. It means that the deputies a and b do not like each other.
There are multiple test cases. Process to end of file.
Output
The text file SPO.OUT should contain one word NIE (means NO in Polish), if the setting up of the Commission is impossible. In case when setting up of the Commission is possible the file SPO.OUT should contain n integers from the interval from 1 to 2n, written in the ascending order, indicating numbers of deputies who can form the Commission. Each of these numbers should be written in a separate line. If the Commission can be formed in various ways, your program may write mininum number sequence.
Sample Input
3 2
1 3
2 4
Sample Output
1
4
5

#include <cstdio>#include <iostream>#include <algorithm>#include <cstring>#include <stack>using namespace std;const int maxn = 8005; //maxnΪn*2const int maxm = 20005; //int n,m; //n¶Ô·òÆÞ£¬m¶Ô»¥³â¹Øϵstruct EdgeNode {    int to;    int next;};struct TwoSAT {    int head[maxn*2];    EdgeNode edges[maxm*2];    int edge,n;    bool mark[maxn*2];    int S[maxn*2],c;    void init(int n) {        this->n=n;        memset(mark,0,sizeof(mark));        memset(head,-1,sizeof(head));        edge=0;    }    void addedge(int u,int v) {        edges[edge].to=v,edges[edge].next=head[u],head[u]=edge++;    }    // x = xval or y = yval    void add_clause(int x,int xval,int y,int yval) {        x=x*2+xval;        y=y*2+yval;        addedge(x^1,y);  //x^1¿ÉÒÔÍƳöy¾Í½¨Á¢Ò»Ìõ¶ÔÓ¦µÄ±ß£¬ÏÂͬ        addedge(y^1,x);    }    // x = xval    void add_con(int x,int xval) {        x=x*2+xval;        addedge(x^1,x);    }    bool dfs(int x) {        if (mark[x^1]) return false; //½ÚµãÒѱ»·ÃÎÊ£¬ÏÂͬ        if (mark[x]) return true;        mark[x]=true;  //±ê¼Çxi        S[c++]=x;        for (int i=head[x]; i!=-1; i=edges[i].next) //ÁÚ½Ó±ßËÑË÷            if (!dfs(edges[i].to)) return false;        return true;    }    bool solve() {        for (int i=0; i<n*2; i+=2)            if (!mark[i]&&!mark[i+1]) {                c=0;                if (!dfs(i)) { //Èç¹û±ê¼ÇxiΪ¼Ù²»³ÉÁ¢£¬Ôò´ÓÍ·±ê¼ÇxiΪÕæ                    while (c>0) mark[S[--c]]=false;//·µ»Ø¼ÙÉèµÄÆðµã                    if (!dfs(i+1)) return false;//ÅжÏÊÇ·ñ³ÉÁ¢                }            }        return true;    }};TwoSAT ts;int main (void) {    ios::sync_with_stdio(false);//  freopen("SPO.IN", "R", stdin);//  freopen("SPO.OUT", "W", stdout);    while(cin>>n>>m) {        ts.init(n);        for(int i=1; i<=m; ++i) {            int a, b;            cin>>a>>b;            a--, b--;            ts.addedge(a, b^1);            ts.addedge(b, a^1);        }        if(ts.solve()) {//      cout<<"YES"<<endl;            for(int i = 0; i < 2*n; i += 2)                if(ts.mark[i])                    cout<<i+1<<endl;                else                    cout<<i+2<<endl;        } else            cout<<"NIE"<<endl;    }    return 0;}