UVA Graph Coloring

主题如以下:

Graph Coloring 

You are to write a program that tries to find an optimal coloring for agiven graph. Colors are applied to the nodes of the graph and the only availablecolors are black and white. The coloring of the graph is called optimalif a maximum of nodes is black. The coloring is restricted by the rule thatno 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 , ,and a set of undirected edges denoted by pairs of node numbers , . The input file contains mgraphs. The number m is given on the first line. The first line ofeach graph contains n and k, the number of nodes and the numberof edges, respectively. The following k lines contain the edges givenby a pair of node numbers, which are separated by a space.

The output should consists of 2m lines, two lines for each graphfound in the input file. The first line of should contain the maximum numberof nodes that can be colored black in the graph. The second line shouldcontain one possible optimal coloring. It is given by the list of blacknodes, separated by a blank.

Sample Input

1
6 8
1 2
1 3
2 4
2 5
3 4
3 6
4 6
5 6

Sample Output

3
1 4 5

求图中黑色节点的最大个数,黑色节点不能相邻,看起来挺简单的(实际上也非常easy。

。),但自己NC,超时又WA了几次,没理解清晰DFS中的cur的含义,我原意cur是推断过的节点个数,但这样确定不了递归边界,假设边界是cur==n,那么每次递归都得推断n个点,非常浪费时间,有些点是明显不可能的。

后来改成cur是当前要推断的点的下标。思路清晰多了,但还存在一个问题:若当前节点不能染色,要不要递归下去?细致想想就会发现,肯定须要递归下去。不然达不到递归边界。但假设当前节点能够染色。是不是仅仅把当前节点染色,然后递归?这样能够过例子。但会WA,由于这样漏掉了非常多情况。这样就相当于从第一个点開始推断。然后第一个点肯定能被染色。然后再依次看其他点,总共就一种方案,但总共同拥有多种染色方案。所以说即使当前节点能够染色,也要递归不染该节点的情况。

AC的代码例如以下:


版权声明:本文博客原创文章,博客,未经同意,不得转载。

你可能感兴趣的:(color)