码迷,mamicode.com
首页 > 其他好文 > 详细

UVA Graph Coloring

时间:2014-07-19 02:35:06      阅读:210      评论:0      收藏:0      [点我收藏+]

标签:acm   brute force   uva   backtracking   

题目如下:

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.

  bubuko.com,布布扣
Figure: An optimal graph with three black nodes

Input and Output

The graph is given as a set of nodes denoted by numbers bubuko.com,布布扣 , bubuko.com,布布扣 ,and a set of undirected edges denoted by pairs of node numbers bubuko.com,布布扣 , bubuko.com,布布扣 . 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

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

AC的代码如下:


UVA Graph Coloring

标签:acm   brute force   uva   backtracking   

原文地址:http://blog.csdn.net/u013840081/article/details/37931413

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!