The Accomodation of Students
There are a group of students. Some of them may know each other, while others don’t. For example, A and B know each other, B and C know each other. But this may not imply that A and C know each other.
Now you are given all pairs of students who know each other. Your task is to divide the students into two groups so that any two students in the same group don’t know each other.If this goal can be achieved, then arrange them into double rooms. Remember, only paris appearing in the previous given set can live in the same room, which means only known students can live in the same room.
Calculate the maximum number of pairs that can be arranged into these double rooms.
Input
For each data set:
The first line gives two integers, n and m(1<n<=200), indicating there are n students and m pairs of students who know each other. The next m lines give such pairs.
Proceed to the end of file.
Output
If these students cannot be divided into two groups, print “No”. Otherwise, print the maximum number of pairs that can be arranged in those rooms.
Sample Input
4 4
1 2
1 3
1 4
2 3
6 5
1 2
1 3
1 4
2 5
3 6
Sample Output
No
3
#include <algorithm>
#include <bitset>
#include <cmath>
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <deque>
#include <functional>
#include <iostream>
#include <map>
#include <queue>
#include <set>
#include <stack>
#include <string>
#include <vector>
using namespace std;
int n, m, flag;
bool g[210][210];
bool book[210];
int c[210]; //颜色,0表示还没有访问,1表示黑色,-1表示白色
int match[210];
void dfs(int i, int color) // 染色法判断G是否为二分图
{
int j;
for (j = 1; j <= n; j++) {
if (g[i][j] == 1) {
if (c[j] == 0) {
c[j] = -color;
dfs(j, -color);
} else if (c[j] == color) {
flag = 0;
return;
}
if (flag == 0) return;
}
}
}
int check() {
flag = 1;
memset(c, 0, sizeof(c));
c[1] = 1; //设一号是黑色,将其相邻的点染成白色
dfs(1, 1); //从一号开始染色
return flag;
}
bool find(int u) {
int i;
for (i = 1; i <= n; i++) {
if (g[u][i] == 1 && book[i] == 0) {
book[i] = 1;
if (match[i] == 0 || find(match[i])) {
match[i] = u;
return 1;
}
}
}
return 0;
}
int main() {
int i, sum, p, q;
while (scanf("%d%d", &n, &m) != EOF) {
memset(g, 0, sizeof(g));
memset(match, 0, sizeof(match));
while (m--) {
scanf("%d%d", &p, &q);
g[p][q] = g[q][p] = 1;
}
if (check() == 0) {
printf("No\n");
continue;
}
sum = 0;
for (i = 1; i <= n; i++) {
memset(book, 0, sizeof(book));
if (find(i)) sum++;
}
printf("%d\n", sum / 2);
}
return 0;
}