给你一个图,问是否为二分图,若是求出最大匹配。
并查集判图,原理黑白染色。
#include <cstdio> #include <cstdlib> #include <cstring> #include <algorithm> #include <cmath> #include <stack> #include <queue> #include <vector> #include <map> #include <string> #include <iostream> using namespace std; int n,m; const int maxn = 555; int link[maxn]; int used[maxn]; int Map[maxn][maxn]; int father[maxn*2]; int getfather(int x) { if(father[x]!=x) father[x]=getfather(father[x]); return father[x]; } int dfs(int x) { for(int i=1;i<=n;i++){ if(Map[x][i]&&!used[i]){ used[i]=1; if(link[i]==-1||dfs(link[i])){ link[i]= x; return 1; } } } return 0; } int gao() { int ans=0; memset(link,-1,sizeof(link)); for(int i=1;i<=n;i++){ memset(used,0,sizeof(used)); ans+=dfs(i); } return ans; } int main() { int a,b; while(cin>>n>>m){ memset(Map,0,sizeof(Map)); for(int i=1;i<=2*n;i++) father[i]= i; int flag=0; for(int i=0;i<m;i++){ scanf("%d%d",&a,&b); int fa=getfather(a);int fb= getfather(b); int fa1= getfather(a+n);int fb1= getfather(b+n); if(fa==fb) flag=1; father[fa]=fb1;father[fb]=fa1; Map[a][b]=1;Map[b][a]=1; } if(flag){ printf("No ");continue; } int t= gao(); printf("%d ",t/2); } return 0; }
bfs判图
#include <cstdio> #include <cstdlib> #include <cstring> #include <algorithm> #include <cmath> #include <stack> #include <queue> #include <vector> #include <map> #include <string> #include <iostream> using namespace std; int n,m; const int maxn = 222; int link[maxn]; int used[maxn]; int Map[maxn][maxn]; int Dye(int x) { int vis[maxn];int color[maxn]; memset(vis,0,sizeof(vis)); memset(color,-1,sizeof(color)); queue<int> q; q.push(x); vis[x]=1; color[x]= 1; while(!q.empty()){ int cur=q.front(); q.pop(); for(int i=1;i<=n;i++){ if(!Map[cur][i])continue; if(color[i]==color[cur]) return 0; color[i]=color[cur]^1; if(!vis[i]){ vis[i]=1 ;q.push(i); } } } return 1; } int dfs(int x) { for(int i=1;i<=n;i++){ if(Map[x][i]&&!used[i]){ used[i]=1; if(link[i]==-1||dfs(link[i])){ link[i]= x; return 1; } } } return 0; } int gao() { int ans=0; memset(link,-1,sizeof(link)); for(int i=1;i<=n;i++){ memset(used,0,sizeof(used)); ans+=dfs(i); } return ans; } int main() { int a,b; while(cin>>n>>m){ memset(Map,0,sizeof(Map)); for(int i=0;i<m;i++){ scanf("%d%d",&a,&b); Map[a][b]=1;Map[b][a]=1; } int flag=0; for(int i=1;i<=n;i++) if(!Dye(i)) flag=1; if(flag){ printf("No ");continue; } int t= gao(); printf("%d ",t/2); } return 0; }