http://acm.zju.edu.cn/onlinejudge/showProblem.do?problemId=4879
把b[][]数组上的每个位拆开成两个点i和i',(不超过32位),另外新加两个点0和1,如果确定某点i对应的是0,则i与0点合并,i'点与1点合并;如果确定某点i对应的是1,则i与1合并,i'与0合并;如果确定两点i和j对应的位是相反的数,则i与j'合并,j与i'合并;如果确定两点对应的位是相同的数,则i与j合并,i'与j'合并。
#include <cstdio> #include <cstring> #include <iostream> #include <algorithm> using namespace std; const int maxn = 100000; int p[maxn]; int b[505][505]; int n; void init() { for(int i=0;i<(2*n+1)*32+100;i++) p[i] = i; } int find(int x) { return x==p[x] ? x : p[x] = find(p[x]); } void Union(int x,int y) { int a = find(x) , b = find(y); p[a] = p[b] = p[x] = p[y] = min(a , b); } bool check() { for(int i=1;i<=n;i++) { for(int j=i+1;j<=n;j++) if(b[i][j] != b[j][i]) return 0; if(b[i][i] != 0) return 0; } init(); int m = 32 * n; for(int i=1;i<=n;i++) for(int j=i+1;j<=n;j++) { if(i % 2 == 0 && j % 2 == 0) { for(int k=0;k<32;k++) { if(b[i][j] & (1<<k) == 0) { int u = i*32+k , v = j*32+k; if(find(u) == find(1) || find(v) == find(1) || find(u) == find(v+m)) return 0; Union(u,0); Union(v,0); Union(u+m,1); Union(v+m,1); } } } else if(i % 2 == 1 && j % 2 == 1) { for(int k=0;k<32;k++) { if(b[i][j] & (1<<k)) { int u = i* 32 + k , v = j*32+k; if(find(u) == find(0) || find(v)==find(0) || find(u) == find(v+m)) return 0; Union(u,1); Union(v,1); Union(u+m,0); Union(v+m,0); } } } else { for(int k=0;k<32;k++) { int u = i * 32 + k , v = j * 32 + k; if(b[i][j] & (1<<k)) { if(find(u) == find(v)) return 0; Union(u,v+m); Union(u+m,v); } else { if(find(u) == find(v+m)) return 0; Union(u,v); Union(u+m,v+m); } } } } return 1; } int main() { while(~scanf("%d",&n)) { for(int i=1;i<=n;i++) for(int j=1;j<=n;j++) scanf("%d",&b[i][j]); if(check()) puts("YES"); else puts("NO"); } return 0; }