hdu1814 Peaceful Commission 2-sat

本文介绍了一种利用位运算解决2-SAT问题的方法,重点在于通过优化算法实现最小序输出,确保奇数变量尽可能前置。通过具体的C++代码示例详细展示了如何构建图并进行深度优先搜索以求解问题。

裸的2-sat 因为要输出最小序所以奇数尽量先放。用位运算就可以巧妙的解决。

#include <cstring>
#include <algorithm>
#include <cstdio>
#include <stack>
#include <iostream>
#include <queue>
#include <vector>
using namespace std;
int n,m,tot;
#define maxn 11000
vector<int>g[maxn<<1];
bool mark[maxn<<1];
stack<int>sta;
bool dfs(int x)
{
    if(mark[x^1]) return false;
    if(mark[x]) return true;
    mark[x] = true;
    sta.push(x);
    for(int i=0; i<g[x].size(); ++i)
        if(!dfs(g[x][i])) return false;
    return true;
}
bool solve()
{
    memset(mark,false,sizeof(mark));
    for(int i=0;i<n;i+=2)
    {
        if(!mark[i]&&!mark[i^1])
        {
            while(!sta.empty())
            {
                sta.pop();
            }
            if(!dfs(i))
            {
                while(!sta.empty())
                {
                    int tmp=sta.top();
                    mark[tmp]=0;
                    sta.pop();
                }
                if(!dfs(i^1))
                {
                    return false;
                }
            }
        }
    }
    return true;
}
int main()
{
    int a,b;
    while(~scanf("%d%d",&n,&m))
    {
        while(!sta.empty())
        {
            sta.pop();
        }
        n<<=1;
        for(int i=0;i<=n;i++)
        {
            g[i].clear();
        }
        while(m--)
        {
            scanf("%d%d",&a,&b);
            a--;
            b--;
            g[a].push_back(b^1);
            g[b].push_back(a^1);
        }
        if(solve())
        {
            for(int i=0; i<n; i+=2)
            {
                if(mark[i])
                    printf("%d\n", i+1);
                else
                    printf("%d\n", (i^1)+1);
            }
        }
        else
        {
            printf("NIE\n");
        }
    }
    return 0;
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值