首页 > 代码库 > poj3648 wedding 2-SAT

poj3648 wedding 2-SAT

#include<iostream>
#include<cstdio>
#include<algorithm>
#include<cstring>
using namespace std;
int n,m;
#include<vector>
#define N 8200
int e[N],v[N],ne[N];
int nn;
void add(int x,int y){
   ne[++nn]=e[x],e[x]=nn,v[nn]=y;    
}
int e2[N],nn2,v2[N],ne2[N];
void add2(int x,int y){
    ne2[++nn2]=e2[x],e2[x]=nn2,v2[nn2]=y;
}
int stn,st[N];
int been[N];
int low[N],dfn[N];
int in[N];
int ru[N],tot,bn;
vector<int> jj[N];
int col[N];
void cl(){
   memset(col,0,sizeof(col));
   memset(been,0,sizeof(been));    
   memset(low,0,sizeof(low));
   memset(dfn,0,sizeof(dfn));
   memset(e,0,sizeof(e));
   memset(e2,0,sizeof(e2));
   memset(ru,0,sizeof(ru));
   nn=0,nn2=0;
   bn=0;
   tot=0;
}
int qu[N],he,bo;
void dfs(int x){
    low[x]=dfn[x]=++tot;
    st[++stn]=x;
    been[x]=1;
    for(int i=e[x];i;i=ne[i]){
        if(!dfn[v[i]]){
           dfs(v[i]);
           low[x]=min(low[x],low[v[i]]);    
        }else if(been[v[i]])low[x]=min(low[x],dfn[v[i]]);
    }
    if(dfn[x]==low[x]){
       bn++;
       do{
            in[st[stn]]=bn;
            been[st[stn]]=0;
        }while(st[stn--]!=x);    
    }
    
}
int main(){
    while(scanf("%d%d",&n,&m),n){
        cl();
        for(int i=1;i<=m;i++){
           int a,b;
           char c,d;
           scanf("%d",&a);
           scanf("%c",&c);
           scanf("%d",&b);
           scanf("%c",&d);
           a++,b++;    
            if(c==h){
               if(d==h)add(a,b+n),add(b,a+n);
               else add(a,b),add(b+n,a+n);    
            }
            if(c==w){
               if(d==h)add(a+n,b+n),add(b,a);
                else add(a+n,b),add(b+n,a);    
            }
        }
        add(1+n,1);
        for(int i=1;i<=n*2;i++)if(!dfn[i])dfs(i);
    
        for(int i=1;i<=n;i++)if(in[i]==in[i+n]){
           printf("bad luck\n");
           goto loop;    
        }
        for(int i=1;i<=n*2;i++){
           for(int j=e[i];j;j=ne[j])if(in[i]!=in[v[j]]){
                add2(in[v[j]],in[i]);
                ru[in[i]]++;
            }    
        }
        for(int i=1;i<=bn;i++)jj[i].clear();
        for(int i=1;i<=n;i++){
            jj[in[i]].push_back(in[i+n]);
            jj[in[i+n]].push_back(in[i]);    
        }
        bo=1;
        he=0;
        for(int i=1;i<=bn;i++){
            if(!ru[i])qu[++he]=i;    
        }
        while(he>=bo){
           int x=qu[bo++];
           
           if(col[x])continue;
           for(int j=0;j<jj[x].size();j++){
                col[jj[x][j]]=1;    
            }
            for(int i=e2[x];i;i=ne2[i]){
                ru[v2[i]]--;
                if(!ru[v2[i]])qu[++he]=v2[i];
            }    
            
        }
        for(int i=2;i<=n;i++)if(col[in[i]]){
            printf("%dh ",i-1);
        }else{
            printf("%dw ",i-1);
        }
        printf("\n");
        loop:;
    }
}