hdu 1814 Peaceful Commission (2-sat入门)

专题和资料


#include<iostream>
#include<cstdio>
#include<algorithm>
#include<cstring>
#include<stack>
#include<vector>
using namespace std;
#define maxn 20005
#define maxm 100005

struct Edge{
    int to,next;
}edge[maxm];

int cnt,head[maxn],S[maxn],top;
bool vis[maxn];

inline void add(int u,int v)
{
    edge[cnt].to=v;
    edge[cnt].next=head[u];
    head[u]=cnt++;
}

bool dfs(int u)
{
    if(vis[u^1]) return 0;
    if(vis[u]) return 1;
    vis[u]=1;
    S[top++]=u;
    for(int i=head[u];~i;i=edge[i].next)
        if(!dfs(edge[i].to)) return 0;
    return 1;
}

bool solve(int n)
{
    memset(vis,0,sizeof(vis));
    for(int i=0;i<n;i+=2)
    {
        if(vis[i]||vis[i^1]) continue;
        top=0;
        if(!dfs(i))
        {
            while(top) vis[S[--top]]=0;
            if(!dfs(i^1)) return 0;
        }
    }
    return 1;
}


int main()
{
    int n,m,i,x,y;
    while(~scanf("%d%d",&n,&m))
    {
        cnt=0;
        memset(head,-1,sizeof(head));
        for(i=0;i<m;++i){
            scanf("%d%d",&x,&y);
            --x,--y;
            add(x,y^1);
            add(y,x^1);
        }
        if(solve(n+n))
        {
            for(i=0;i<2*n;++i)
                if(vis[i]) printf("%d\n",i+1);
        }
        else puts("NIE");
    }
    return 0;
}



你可能感兴趣的:(hdu 1814 Peaceful Commission (2-sat入门))