poj 3678 2-sat 建图非常容易错!!
改天把2-sat刷完了再一起总结吧,先放这儿
#include<stdio.h> #include<string.h> #include<vector> #include<algorithm> using namespace std; const int MAX =20010; vector<int> edge[MAX]; int st[MAX]; int dfn[MAX],low[MAX]; int top,btype,tdfn; int belong[MAX]; bool ins[MAX]; void dfs(int s) { int i,t; dfn[s]=low[s]=++tdfn; ins[s]=true; st[++top]=s; for(i=0;i<edge[s].size();i++) { t=edge[s][i]; if(!dfn[t]) { dfs(t); if(low[t]<low[s]) low[s]=low[t]; } else if(ins[t] && dfn[t]<low[s]) low[s]=dfn[t]; } if(dfn[s]==low[s]) { btype++; do { t=st[top--]; ins[t]=false; belong[t]=btype; }while(t!=s); } } void SCC(int n) { int i; top=btype=tdfn=0; memset(ins,false,sizeof(ins)); memset(dfn,0,sizeof(dfn)); for(i=1;i<=n;i++) if(!dfn[i]) dfs(i); } int main() { int i,j,k; int n,m; int a,b,c; scanf("%d%d",&n,&m); char str[5]; for(i=0;i<m;i++) { scanf("%d%d%d%s",&a,&b,&c,str); a++,b++; if(strcmp(str,"AND")==0) { if(c==0) { edge[b+n].push_back(a); edge[a+n].push_back(b); } else { edge[a+n].push_back(b+n); edge[b+n].push_back(a+n); edge[a].push_back(a+n); edge[b].push_back(b+n); } } else if(strcmp(str,"OR")==0) { if(c==0) { edge[a].push_back(b); edge[b].push_back(a); edge[a+n].push_back(a); edge[b+n].push_back(b); } else { edge[a].push_back(b+n); edge[b].push_back(a+n); } } else { if(c==0) { edge[a].push_back(b); edge[b].push_back(a); edge[a+n].push_back(b+n); edge[b+n].push_back(a+n); } else { edge[a].push_back(b+n); edge[b].push_back(a+n); edge[a+n].push_back(b); edge[b+n].push_back(a); } } } SCC(2*n); int flag=1; for(i=1;i<=n;i++) { if(belong[i]==belong[i+n]) { flag=0; break; } } if(flag==0) printf("NO\n"); else printf("YES\n"); return 0; }