4 4 1 2 1 3 1 4 2 3 6 5 1 2 1 3 1 4 2 5 3 6
No 3
题意:给你一些n个点,m条双向边,判断图是不是二分图,是的话求出最大匹配。
#include<cstring>
#include<cstdio>
#include<iostream>
#include<algorithm>
#include<cmath>
#include<vector>
#define N 222
using namespace std;
int n,m;
vector<int>G[N];
int linker[N];
bool used[N];
int c[N];
int maze[N][N];
bool dfs(int u) {
int v;
for(v=0; v<G[u].size(); v++) {
int i=G[u][v];
if(!used[i]) {
used[i]=true;
if(linker[i]==-1||dfs(linker[i])) {
linker[i]=u;
return true;
}
}
}
return false;
}
int hungary() {
int res=0;
int u;
memset(linker,-1,sizeof(linker));
for(u=1; u<=n; u++) {
memset(used,0,sizeof(used));
if(dfs(u)) res++;
}
return res;
}
bool dfs_c(int pos,int col) {
for(int i=0; i<G[pos].size(); i++) {
int v=G[pos][i];
if(c[v]==c[pos])
return false;
if(!c[v]) {
c[v]=-col;
if(!dfs_c(v,-col))return false;
}
}
return true;
}
///染色法判断二分图
bool color() {
memset(c,0,sizeof c);
int col=1;
for(int i=1; i<=n; i++) {
if(c[i]!=0)continue;
c[i]=col;
if(!dfs_c(i,col)) {
return false;
}
}
return true;
}
int main() {
//freopen("in.txt","r",stdin);
while(~scanf("%d%d",&n,&m)) {
for(int i=0; i<N; i++)G[i].clear();
int x,y;
for(int i=0; i<m; i++) {
scanf("%d%d",&x,&y);
G[x].push_back(y);
G[y].push_back(x);
}
if(!color()) {
printf("No\n");
continue;
}
printf("%d\n", hungary()/2);
}
return 0;
}
hdu The Accomodation of Students(二分匹配)
原文地址:http://blog.csdn.net/acm_baihuzi/article/details/45727947