題目:給一個有向圖染色,每個節點可以染成黑色或者白色,相鄰的節點不能同時染成黑色,
問最多能有多少個黑色節點,并輸出;
分析:圖論、搜索。直接按順序枚舉接節點,回溯計算即可,最大團╮(╯▽╰)╭。
說明:忽略了每次去下一個節點是取不到終點的情況,WA了好幾次╮(╯▽╰)╭。
#include <cstring>
#include <cstdio>
int maps[105][105], save[105], color[105], ans;
void dfs(int s, int n, int c)
{
if (s > n) {
if (ans < c) {
ans = c;
for (int j = 1; j <= n; ++ j)
save[j] = color[j];
}
return;
}
for (int i = s; i <= n; ++ i)
if (!color[i]) {
color[i] = i;
for (int j = 1; j <= n; ++ j)
if (maps[i][j] && color[j] == 0)
color[j] = i;
int now = i+1;//防止不能到达终点
while (color[now]) now ++;
dfs(now, n, c+1);
for (int j = 1; j <= n; ++ j)
if (color[j] == i)
color[j] = 0;
}
}
int main()
{
int m, n, k, v, u;
while (~scanf("%d",&m))
while (m --) {
scanf("%d%d",&n,&k);
memset(maps, 0, sizeof(maps));
memset(color, 0, sizeof(color));
for (int i = 1; i <= k; ++ i) {
scanf("%d%d",&v,&u);
maps[v][u] = maps[u][v] = 1;
}
ans = 0;
dfs(1, n, 0);
printf("%d\n",ans);
int start = 0;
for (int i = 1; i <= n; ++ i) {
if (save[i] == i) {
if (start) printf(" ");
start = 1;
printf("%d",i);
}
}
puts("");
}
return 0;
}