首页 > 代码库 > 二分图

二分图

BFS版:

 1 #include <bits/stdc++.h>
 2 using namespace std;
 3 
 4 const int maxn=100000+15;
 5 struct Edge {
 6     int x,y,next;
 7     Edge(int x=0,int y=0,int next=0):
 8         x(x),y(y),next(next) {}
 9 } edge[maxn*2];
10 int sumedge,head[maxn];
11 int n,m;
12 int ins(int x,int y) {
13     edge[++sumedge]=Edge(x,y,head[x]);
14     return head[x]=sumedge;
15 }
16 int h,t,que[maxn];
17 int col[maxn];
18 int main() { //假设连通
19     scanf("%d%d",&n,&m);
20     for (int i=1; i<=m; i++) {
21         int x,y;
22         scanf("%d%d",&x,&y);
23         ins(x,y);
24         ins(y,x);
25     }
26     memset(col,-1,sizeof(col));
27     que[h=t=1]=1;   //染色序列
28     col[1]=0;   //初始染色
29     for (; h<=t; h++) {
30         int x=que[h];
31         for (int u=head[x]; u; u=edge[u].next)
32             if (col[edge[u].y]!=-1) { //已经染过色
33                 if (col[edge[u].y]==col[x]) { //check
34                     printf("Wrong!\n");
35                     return 0;
36                 }
37             } else {
38                 col[edge[u].y]=col[x]^1;  //染色
39                 que[++t]=edge[u].y;
40             }
41     }
42     return 0;
43 }

并查集版:

 1 #include <bits/stdc++.h>
 2 using namespace std;
 3 
 4 const int maxn=100000+15;
 5 int n,m,top[maxn*2];
 6 int found(int x) {
 7     if (top[x]==x) return x;
 8     top[x]=found(top[x]);
 9     return top[x];
10 }
11 int main() {
12     scanf("%d%d",&n,&m);
13     for (int i=1; i<=2*n; i++) top[i]=i;
14     for (int i=1; i<=m; i++) {
15         int x,y;
16         scanf("%d%d",&x,&y);
17         int fx=found(2*x-1),fy=found(2*y);
18         //一个染白则另一个染黑
19         top[fx]=fy;
20         fx=found(2*x),fy=found(2*y-1);
21         //一个染黑则另一个染白
22         top[fx]=fy;
23     }
24     for (int i=1; i<=n; i++)
25         if (found(2*i-1)==found(2*i)) { //check
26             printf("Wrong!\n");
27             return 0;
28         }
29     return 0;
30 }

 

二分图