题目意思就是给出一个图,先判断是不是二分图,如果不是输出no,否则输出最大匹配数。
判断是不是二分图可以用bfs,也可以用dfs。无非就是选择一个点,先染成黑色,再判断周围的点有没有染色,没有染色则染成白色,继续把其他点染色。如果染色了且颜色也是黑色,则不是二分图,颜色不同则继续染色。
这道题题目给的不是已经建好的二分图形式,也就是x集合和y集合没有明确的分开。所以我们要建成无向图,最后答案是我们算的最大匹配数的一半。
#pragma warning(disable:4996);
#include <algorithm>
#include <iostream>
#include <cstring>
#include <cstdlib>
#include <cstdio>
#include <cmath>
#include <queue>
#include <new>
#include <set>
#include <map>
using namespace std;
typedef long long int LL;
const double pi = (acos(-1));
const int maxn = 1000;
int g[maxn][maxn], used[maxn], link[maxn];
int nx, ny, n, m;
bool dfs (int u) {
for (int v = 1; v <= n; v++) {
if (g[u][v] && !used[v]) {
used[v] = 1;
if (link[v] == -1 || dfs (link[v])) {
link[v] = u;
return true;
}
}
}
return false;
}
int maxmatch () {
int res = 0;
memset (link, -1, sizeof (link));
for (int i = 1; i <= n; i++) {
memset (used, 0, sizeof (used));
if (dfs (i)) res++;
}
return res / 2;
}
int color[maxn];
bool dye (int u) {
for (int v = 1; v <= n; v++) {
if (g[u][v]) {
if (color[v] == -1) {
color[v] = !color[u];
if (!dye (v)) return false;
}
else if (color[v] == color[u]) return false;
}
}
return true;
}
int main()
{
//freopen("D:\\Test_in.txt", "r", stdin);
//freopen("D:\\Test_out.txt", "w", stdout);
while (~scanf ("%d%d", &n, &m)) {
memset (g, 0, sizeof (g));
for (int i = 0; i < m; i++) {
int u, v;
scanf ("%d%d", &u, &v);
g[u][v] = g[v][u] = 1;
}
memset (color, -1, sizeof (color));
int ok = 1;
for (int i = 1; i <= n; i++) {//染色,可能不止一个连通分量
if (color[i] == -1) {
color[i] = 1;
if (!dye (i)) {
ok = 0;
break;
}
}
}
if (ok) printf ("%d\n", maxmatch ());
else printf ("No\n");
}
return 0;
}