模板。注意若x=y不一定是废话,x=0或x=0表示x必须为0。以及数组开2n。
#include<iostream> #include<cstdio> #include<cmath> #include<cstdlib> #include<cstring> #include<algorithm> using namespace std; int read() { int x=0,f=1;char c=getchar(); while (c<'0'||c>'9') {if (c=='-') f=-1;c=getchar();} while (c>='0'&&c<='9') x=(x<<1)+(x<<3)+(c^48),c=getchar(); return x*f; } #define N 2000010 int n,m,p[N],t=0; int dfn[N],low[N],stk[N],set[N],top=0,cnt=0; bool flag[N]; struct data{int to,nxt; }edge[N]; void addedge(int x,int y){t++;edge[t].to=y,edge[t].nxt=p[x],p[x]=t;} void tarjan(int k) { dfn[k]=low[k]=++cnt; stk[++top]=k;flag[k]=1; for (int i=p[k];i;i=edge[i].nxt) if (!dfn[edge[i].to]) tarjan(edge[i].to),low[k]=min(low[k],low[edge[i].to]); else if (flag[edge[i].to]) low[k]=min(low[k],dfn[edge[i].to]); if (dfn[k]==low[k]) { t++; while (stk[top]!=k) { set[stk[top]]=t; flag[stk[top]]=0; top--; } set[k]=t;flag[k]=0;top--; } } int main() { #ifndef ONLINE_JUDGE freopen("2-SAT.in","r",stdin); freopen("2-SAT.out","w",stdout); const char LL[]="%I64d"; #else const char LL[]="%lld"; #endif n=read(),m=read(); for (int i=1;i<=m;i++) { int x=read(),w=read(),y=read(),v=read(); if (x!=y) addedge(x*2-(w^1),y*2-v),addedge(y*2-(v^1),x*2-w); else if (w==v) addedge(x*2-(w^1),x*2-w); } t=0; for (int i=1;i<=n*2;i++) if (!dfn[i]) tarjan(i); for (int i=1;i<=n;i++) if (set[i<<1]==set[i*2-1]) {cout<<"IMPOSSIBLE";return 0;} cout<<"POSSIBLE "; for (int i=1;i<=n;i++) if (set[i<<1]<set[i*2-1]) printf("0 ");else printf("1 "); return 0; }