和平委员会 2-SAT

Problem

  • 如果a1和b1不能同时出现
  • 就连一条边a1->b0&b1->a0
  • 暴力寻找合法解即可

Code


#include
#define rep(i,a,b) for(int i=(a);i<=(b);i++)
using namespace std;
const int N=2e5;
struct node{int y,n;}e[N];
int lin[N],v[N],ans[N],len=0,cnt,a,b,n,m;
void read(int x,int y){
    e[++len].y=y,e[len].n=lin[x],lin[x]=len;
}
void init(){
    memset(e,0,sizeof(e));
    memset(v,0,sizeof(v));
    memset(lin,0,sizeof(lin));
    memset(ans,0,sizeof(ans));
    len=0;
}
bool dfs(int x){
    if(v[x]==2)return 0;
    if(v[x]==1)return 1;
    v[x]=1,v[x^1]=2,ans[cnt++]=x;
    for(int i=lin[x];i;i=e[i].n){
        int y=e[i].y;
        if(!dfs(y))return 0;
    }return 1;
}
bool solve(){
    rep(i,0,n-1){
        if(v[i])continue;
        cnt=0;
        if(!dfs(i)){
            rep(j,0,cnt-1){
                v[ans[j]]=0;
                v[ans[j]^1]=0;
            }if(!dfs(i^1))return 0;
        }
    }return 1;
}
int main()
{
    //freopen("a.in","r",stdin);
    while(~scanf("%d%d",&n,&m)){
        n<<=1; init();
        while(m--){
            scanf("%d%d",&a,&b);
            a--,b--;
            read(a,b^1),read(b,a^1);
        }
        if(solve()){
            rep(i,0,n-1)if(v[i]==1)printf("%d\n",i+1);
        }else puts("NIE");
    }return 0;
}

 

你可能感兴趣的:(图论)