Description
You are to write a program that tries to find an optimal coloring for a given graph. Colors are applied to the nodes of the graph and the only available colors are black and white. The coloring of the graph is called optimal if a maximum of nodes is black. The coloring is restricted by the rule that no two connected nodes may be black.
Figure: An optimal graph with three black nodes
Input and Output
The graph is given as a set of nodes denoted by numbers tex2html_wrap_inline33 , tex2html_wrap_inline35 , and a set of undirected edges denoted by pairs of node numbers tex2html_wrap_inline37 , tex2html_wrap_inline39 . The input file contains m graphs. The number m is given on the first line. The first line of each graph contains n and k, the number of nodes and the number of edges, respectively. The following k lines contain the edges given by a pair of node numbers, which are separated by a space. The output should consists of 2m lines, two lines for each graph found in the input file. The first line of should contain the maximum number of nodes that can be colored black in the graph. The second line should contain one possible optimal coloring. It is given by the list of black nodes, separated by a blank.
Sample Input
Sample Output
题意: 一开始题意理解错了。题意是这样的,给出一个图,让你染成黑白两种颜色,但是相连的两点不能都染成黑色,问最多能染色多少的黑色点。
思路:直接dfs回溯,庆幸的是没有超时。dfs(int u/*u表示当前正在判断的点*/,int num/*num表示黑点的数量*/),u初值为1,num初值为0,然后分为两种情况,第一种情况先判断与当前点u相连的点有没有染成黑色的,如果有的话直接把当前点u染成白色,(即dfs(u+1,num);return;),否则进入第二种情况:将当前点u染成黑色或者白色。
if(u>=n+1)边界限制,ans取更大值。最后输出的格式注意。
AC代码:
#pragma comment(linker, "/STACK:1024000000,1024000000")
#include<iostream>
#include<cstdio>
#include<cstring>
#include<cmath>
#include<math.h>
#include<algorithm>
#include<queue>
#include<set>
#include<bitset>
#include<map>
#include<vector>
#include<stdlib.h>
#include <stack>
using namespace std;
#define PI acos(-1.0)
#define max(a,b) (a) > (b) ? (a) : (b)
#define min(a,b) (a) < (b) ? (a) : (b)
#define ll long long
#define eps 1e-10
#define MOD 1000000007
#define N 106
#define inf 1e12
int n,m;
int mp[N][N];
int ans;
int color[N];
int res[N];
void dfs(int u/*u表示当前正在判断的点*/,int num/*num表示黑点的数量*/){
if(u>=n+){
if(ans<num){
ans=num;
for(int i=;i<=n;i++){
res[i]=color[i];
}
}
return;
} for(int i=;i<=n;i++){
if(mp[u][i] && color[i]){
dfs(u+,num);//只能染成白色的情况,否则下面的情况能染成黑色或白色
return;
}
}
color[u]=;
dfs(u+,num+);//能染成黑色 color[u]=;
dfs(u+,num);//能染成白色 }
int main()
{
int t;
scanf("%d",&t);
while(t--){
memset(mp,,sizeof(mp));
scanf("%d%d",&n,&m);
for(int i=;i<m;i++){
int a,b;
scanf("%d%d",&a,&b);
mp[a][b]=mp[b][a]=;
}
ans=;
memset(color,,sizeof(color));
dfs(,); printf("%d\n",ans);
int w=;
for(int i=;i<=n;i++){
if(res[i]){
w++;
printf("%d",i);
if(w!=ans){
printf(" ");
}
} }
printf("\n"); }
return ;
}