Description:
Input:
Output:
Sample Input:
Sample Output:
#include<stdio.h> #include<queue> #include<string.h> #include<algorithm> #define N 210 using namespace std; int G[N][N], visit[N]; int vis[N], use[N], col[N]; int n, flag; void BFS(int u) //判断是否为二分图 { int i, v; queue<int>Q; Q.push(u); visit[u] = 1; while (!Q.empty()) { v = Q.front(); Q.pop(); for (i = 1; i <= n; i++) { if (v == i) continue; if (!visit[i] && col[i] == 0 && G[v][i]) { col[i] = -1; visit[i] = 1; //第一组的学生标记为1,他们的朋友标记为-1,若在查找中发现自己和朋友的标记一致,则说明不能分为互不认识的两组 Q.push(i); } else if (col[i] == col[v] && G[v][i]) flag = 1; //自己和朋友标记相同,则不是二分图 } } } int Find(int u) //匈牙利算法查找最大匹配数 { int i; for (i = 1; i <= n; i++) { if (!vis[i] && G[u][i]) { vis[i] = 1; if (!use[i] || Find(use[i])) { use[i] = u; return 1; } } } return 0; } int main () { int m, ans, i, a, b; while (scanf("%d%d", &n, &m) != EOF) { memset(G, 0, sizeof(G)); memset(use, 0, sizeof(use)); memset(visit, 0, sizeof(visit)); memset(col, 0, sizeof(col)); ans = 0; while (m--) { scanf("%d%d", &a, &b); G[a][b] = 1; } flag = 0; col[1] = 1; BFS(1); if (flag) printf("No\n"); else { for (i = 1; i <= n; i++) { memset(vis, 0, sizeof(vis)); if (Find(i)) ans++; } printf("%d\n", ans); } } return 0; }
HDU 2444 The Accomodation of Students(BFS判断是否为二分图)
原文:http://www.cnblogs.com/syhandll/p/4721270.html