题意:给出一些相连的点,初始均为白色。现在将其中的一些点染成黑色,但是相邻的两个点不能同时为黑色。问最多有多少个黑点,并且把这些点输出。
思路:dfs。
#include<iostream>
#include<string.h>
using namespace std;
int map[105][105];
int sumStep,tmp,step[105];
int color[105];
int n,m;
void dfs(int t)
{
int flag;
for(color[t]=0; color[t]<=1; color[t]++) //color[t]表示第t个点的颜色,0为白,1为黑
{
flag=0;
if(color[t])
{
for(int i=1; i<t; i++)//判断t点以前的与其相连的点是否为黑
if(color[i]&&map[i][t])
{
flag=1;
break;
}
}
if(flag)
continue;
tmp+=color[t];
if(t<n)
dfs(t+1);
else
{
if(sumStep<tmp)
{
sumStep=tmp;
for(int i=1; i<=n; i++)//每次都要更换数组step
step[i]=color[i];
}
}
tmp-=color[t];//回溯
}
}
int main()
{
int tt;
int a,b;
cin>>tt;
while(tt--)
{
memset(map,0,sizeof(map));
sumStep=0;
tmp=0;
cin>>n>>m;
while(m--)
{
cin>>a>>b;
map[a][b]=map[b][a]=1;
}
dfs(1);
cout<<sumStep<<endl;
for(int i=1; i<=n; i++)
if(step[i])
cout<<i<<" ";
cout<<endl;
}
return 0;
}
/*
1
6 8
1 2
1 3
2 4
2 5
3 4
3 6
4 6
5 6
*/