首页 > 代码库 > UVA Graph Coloring

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.

  figure22
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 numberstex2html_wrap_inline37 ,tex2html_wrap_inline39 . The input file containsmgraphs. The number m is given on the first line. The first line ofeach graph containsn and k, the number of nodes and the numberof edges, respectively. The followingk 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

求图中黑色节点的最大个数,黑色节点不能相邻,看起来挺简单的(实际上也很简单。。。),但自己NC,超时又WA了几次,没理解清楚DFS中的cur的含义,我原意cur是判断过的节点个数,但这样确定不了递归边界,如果边界是cur==n,那么每次递归都得判断n个点,很浪费时间,有些点是明显不可能的。后来改成cur是当前要判断的点的下标,思路清晰多了,但还存在一个问题:若当前节点不能染色,要不要递归下去?仔细想想就会发现,肯定需要递归下去,不然达不到递归边界。但如果当前节点可以染色,是不是只把当前节点染色,然后递归?这样可以过样例,但会WA,因为这样漏掉了很多情况,这样就相当于从第一个点开始判断,然后第一个点肯定能被染色,然后再依次看其它点,总共就一种方案,但总共有多种染色方案,所以说即使当前节点可以染色,也要递归不染该节点的情况。

AC的代码如下:

<script src="https://code.csdn.net/snippets/429832.js" type="text/javascript"></script>

UVA Graph Coloring