POJ (DFS+回溯) Graph Coloring

Graph Coloring
Time Limit: 1000MS   Memory Limit: 10000K
Total Submissions: 4271   Accepted: 1942   Special Judge

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. 


POJ (DFS+回溯) Graph Coloring_第1张图片 
Figure 1: An optimal graph with three black nodes 

Input

The graph is given as a set of nodes denoted by numbers 1...n, n <= 100, and a set of undirected edges denoted by pairs of node numbers (n1, n2), n1 != n2. 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.

Output

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

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

Source

Southwestern European Regional Contest 1995
#include <cstdio>
#include <iostream>
#include <cstring>

using namespace std;
int color[105],mark[105],map[105][105];
int t,n,m,mx;

int dfs(int x, int num)///表示在深搜完i各1节点(到第i个节点)时最大的可涂黑节点数
{
    if(mx<num)
    {
        mx=num;
        for(int i=1; i<=n; i++)
            mark[i]=color[i];
    }
    if(num+n-x+1<=mx)
        return 0;
    int flag=1;
   for(int i=1; i<=n; i++)
    if(map[i][x]&&color[i]==1)
   {
       flag=0;
        break;
   }
   if(flag)
   {
       color[x]=1;
       dfs(x+1,num+1);
       color[x]=0;///回溯法
   }
   dfs(x+1,num);
}

int main()
{
    cin>>t;
    while(t--)
    {
         mx=0;
        memset(color,0,sizeof(color));
        memset(mark,0,sizeof(mark));
        cin>>n>>m;
        int a,b;
        for(int i=1; i<=m; i++)
        {
            cin>>a>>b;
            map[a][b]=1;
            map[b][a]=1;
        }
        dfs(1,0);
        cout<<mx<<endl;
        for(int i=1; i<=n; i++)
            if(mark[i])
            cout<<i<<" ";
            cout<<endl;
    }
    return 0;
}

你可能感兴趣的:(ACM,poj)