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 numbers tex2html_wrap_inline37 , tex2html_wrap_inline39 . 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的代码如下:

#include 
   
   
    
    

using namespace std;
int G[150][150];
int MAX;
int flag[150];
int temp[150];
int vis[150];
int n,k;
void dfs(int cur,int sum)
{
    if(cur==n+1)
    {
        if(MAX
    
    
     
     >m;
    while(m--)
    {

        cin>>n>>k;
        memset(G,0,sizeof G);
        memset(flag,0,sizeof flag);
        memset(temp,0,sizeof temp);
        memset(vis,0,sizeof vis);
        for(int i=0; i
     
     
      
      >a>>b;
            G[a][b]=G[b][a]=1;
        }
        MAX=0;
        dfs(1,0);

        cout<
      
      
       
       <
       
        

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值