题意:
给你一个图,让你然后染成黑色和白色,尽可能多的节点染成黑色,但相邻节点不能都是黑色。
思路:
node[i]=1即将i节点染成黑色,为0则表示为白色,默认所有节点为白色,总共就黑白两种情况 ,Judge可以了就黑色,然后白色。回溯。
代码如下:
#include <iostream>
#include <cstdio>
#include <cstring>
#include <algorithm>
using namespace std;
//hei 1 -- bai 0
const int N = 105;
int n, m, maxn;
int node[N], ege[N][N],ans[N];
int Judge(int u) {
for (int i = 1; i <= n; i++)
if (ege[u][i] && node[i])
return false;
return true;
}
void dfs(int cur) {
if (cur == n +1) {
int temp = 0;
for (int i = 1; i <= n; i++) {
if (node[i])
temp++;
}
if (maxn < temp) {
maxn = temp;
int j = 0;
for (int i = 1; i <= n; i++)
if (node[i])
ans[j++] = i;
}
return;
}
node[cur] = 1;
if (Judge(cur))
dfs(cur + 1);
node[cur] = 0;
dfs(cur + 1);
}
int main() {
int cas;
scanf("%d", &cas);
while (cas--) {
memset(ege, 0, sizeof(ege));
memset(node, 0, sizeof(node));
memset(ans, 0, sizeof(ans));
scanf("%d%d", &n, &m);
int u, v;
for (int i = 1; i <= m; i++) {
scanf("%d%d", &u, &v);
ege[u][v] = ege[v][u] = 1;
}
maxn = -1;
dfs(1);
printf("%d\n%d", maxn, ans[0]);
for (int i = 1; i < maxn; i++) {
if (ans[i])
printf(" %d", ans[i]);
}
printf("\n");
}
}