标签:desc ted ems cat ++ cannot mono false sub
经典2sat裸题,dfs的2sat能够方便输出字典序最小的解...
3 2 1 3 2 4
1 4 5
#include <iostream>
#include <cstdio>
#include <cstring>
#include <algorithm>
using namespace std;
const int maxn=100000;
struct Edge
{
int to,next;
}edge[maxn];
int Adj[maxn],Size;
void init()
{
Size=0; memset(Adj,-1,sizeof(Adj));
}
void Add_Edge(int u,int v)
{
edge[Size].to=v;
edge[Size].next=Adj[u];
Adj[u]=Size++;
}
bool vis[maxn];
int top,S[maxn];
bool dfs(int x)
{
if(vis[x^1]) return false;
if(vis[x]) return true;
S[top++]=x; vis[x]=true;
for(int i=Adj[x];~i;i=edge[i].next)
{
if(!dfs(edge[i].to)) return false;
}
return true;
}
bool SAT2(int n)
{
memset(vis,false,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]]=false;
if(!dfs(i^1)) return false;
}
}
return true;
}
int main()
{
int n,m,a,b;
while(scanf("%d%d",&n,&m)!=EOF)
{
init();
while(m--)
{
scanf("%d%d",&a,&b);
a--;b--;
Add_Edge(a,b^1);
Add_Edge(b,a^1);
}
bool t=SAT2(2*n);
if(t)
{
for(int i=0;i<2*n;i++)
{
if(vis[i])
printf("%d\n",i+1);
}
}
else puts("NIE");
}
return 0;
}
标签:desc ted ems cat ++ cannot mono false sub
原文地址:http://www.cnblogs.com/wzjhoutai/p/6715462.html