裸的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;
}

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

被折叠的 条评论
为什么被折叠?



