hdu 4751 Divide Groups (反向建图,判断二分图,交叉染色法)

hdu 4751 题目链接

题意:n个人,给出每个人认识的人的信息。问能否将这些人分成两组,保证每组至少1个人,并且两两互相认识。

思路:首先是反向建图。由于要求同组内两个人互相认识,那么两个人u,v,只要u不认识v或者v不认识有一个满足,就连接双向边u,v,表示u,v不能分到同一组。

由于图反向以后不保证联通,因此求补图以后可能会得到几个联通分量。

而合法的条件是,每个联通分量都合法。

不合法的条件是,只要由一个联通分量不合法。

以及:之前把交叉染色部分写错了。上道题可以通过纯粹是因为数据水。。?

 1/* ***********************************************
 2Author :111qqz
 3Created Time :2016年09月01日 星期四 01时13分04秒
 4File Name :code/hdu/4751.cpp
 5************************************************ */
 6#include <cstdio>
 7#include <cstring>
 8#include <iostream>
 9#include <algorithm>
10#include <vector>
11#include <queue>
12#include <set>
13#include <map>
14#include <string>
15#include <cmath>
16#include <cstdlib>
17#include <ctime>
18#define fst first
19#define sec second
20#define lson l,m,rt<<1
21#define rson m+1,r,rt<<1|1
22#define ms(a,x) memset(a,x,sizeof(a))
23typedef long long LL;
24#define pi pair < int ,int >
25#define MP make_pair
26using namespace std;
27const double eps = 1E-8;
28const int dx4[4]={1,0,0,-1};
29const int dy4[4]={0,-1,1,0};
30const int inf = 0x3f3f3f3f;
31const int N=205;
32int n;
33bool know[N][N];
34int col[N];
35vector<int>edge[N];
36bool dfs( int u,int x)
37{
38    col[u] = x;
39    int siz = edge[u].size();
40    for ( int i = 0 ; i < siz;  i++)
41    {
42	int v  = edge[u][i];
43	if (col[v]==x) return false;
44	if (col[v]==1-x) continue;
45	if (!dfs(v,1-x)) return false;
46    }
47    return true;
48}
49bool ok()
50{
51    for ( int i = 1 ; i <= n ; i++)  //每个联通分量都合法才合法。
52	if (col[i]==-1)
53	    if (!dfs(i,0)) return false;
54    return true;
55}
56int main()
57{
58	#ifndef  ONLINE_JUDGE 
59	freopen("code/in.txt","r",stdin);
60  #endif
61	while (~scanf("%d",&n))
62	{
63	    ms(col,-1);
64	    for ( int i = 0 ; i <= n ;i++) edge[i].clear();
65	    ms(know,false);
66	    for ( int i = 1 ; i <= n ; i++)
67	    {
68		int x;
69		while (~scanf("%d",&x)&&x!=0)
70		{
71		    know[i][x] = true;
72		}
73	    }
74	    for ( int i = 1 ; i <= n ; i++)
75		for ( int j = i+1 ; j <= n ; j++)
76		{
77		    if (know[i][j]&&know[j][i]) continue;
78		   // cout<<"i:"<<i<<" j:"<<j<<endl;
79		    edge[i].push_back(j);
80		    edge[j].push_back(i);
81		}
82	    if (ok())
83		puts("YES");
84	    else puts("NO");
85	}
86  #ifndef ONLINE_JUDGE  
87  fclose(stdin);
88  #endif
89    return 0;
90}