二分图--黑白染色P1330 封锁阳光大学

黑白染色判断是否是二分图*封锁阳光大学

 1 #include <iostream>
 2 #include <algorithm>
 3 #include <cstdio>
 4 #include <cstring>
 5 using namespace std;
 6 const int maxn=5100000;
 7 int t,tot,head[maxn],vis[maxn],color[maxn];
 8 int ans=0,ans1=0,ans2=0;
 9 bool flag;
10 struct node{
11     int to,next;
12 }ed[maxn];
13 void add(int u,int v){
14     ed[++tot].to=v;
15     ed[tot].next=head[u];
16     head[u]=tot;
17 }
18 void dfs(int u,int col){
19     if(vis[u]){
20         if(color[u]!=col)flag=false;
21     }
22     vis[u]=true;
23     if (col==1) color[u]=2,ans1++;
24     else if (col==2) color[u]=1,ans2++;
25     for (int i = head[u];i;i=ed[i].next){
26         int to=ed[i].to;
27         if (vis[to]){
28             if (color[to]==color[u]) flag=false;
29         }
30         else dfs(to,color[u]);
31     }
32 }
33 int main(){
34         memset(ed,0,sizeof(ed));
35         memset(vis,0,sizeof(vis));
36         memset(head,0,sizeof(head));
37         memset(color,0,sizeof(color));
38         flag=true;
39         int n,m;
40         scanf ("%d%d",&n,&m);
41         for (int i = 1;i <= m;i++){
42             int x,y;
43             scanf ("%d%d",&x,&y);
44             add(x,y);add(y,x);
45         }
46         for (int i = 1;i <= n;i++){
47             if (!vis[i]){
48                 ans1=0,ans2=0;
49                 dfs(i,1);
50                 if (flag) ans+=min(ans1,ans2);
51                 if (!flag) {break;}
52             }
53         }
54         if (flag) cout<<ans<<endl;
55         else cout<<"Impossible"<<endl;
56     return 0;
57 } 

树状数组

并查集

原文地址:https://www.cnblogs.com/very-beginning/p/13449454.html