Graph Coloring
Time Limit: 1000MS | Memory Limit: 10000K | |||
Total Submissions: 5029 | Accepted: 2340 | 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.
Figure 1: An optimal graph with three black nodes
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
题目大意:
求一个图的最大独立集(一个顶点集合,其中任意两个顶点之间没有边相连)。
解题思路:
求最大独立集是一个NP难问题,目前没有多项式时间内的解法,所以常见解法就是搜索了。
首先要说一下什么是团:团是一个图的子图,并且这个子图示完全图。那么最大团就是顶点数最多的团。
对于求解最大独立集通常我们转换为求补图的最大团(可以随便画几个图,就可以直观的感受到这两个是完全等价的,并且转换之后平均耗时要少很多)。
我使用了A*搜索,最终用时32Ms,还算比较快啦。主要思想就是维护当前选择的点,然后只选择与已经和所有已选择的点都相邻的点。具体剪枝见代码。
AC代码:
#include <iostream>
#include <algorithm>
#include <cstdio>
#include <cstring>
#include <vector>
#include <queue>
using namespace std;
#define mem(a,b) memset((a),(b),sizeof(a))
const int MAXV=100+3;
int V,E,ans;
bool G[MAXV][MAXV];//补图
int the_max[MAXV];//在第i个到最后一个点形成的子图中最大团的大小
int save[MAXV];//最大团
int select[MAXV];//当前团
void init()//初始化
{
for(int i=1;i<=V;++i)
{
for(int j=1;j<=V;++j)
G[i][j]=true;
}
ans=0;
}
void dfs(int u,int num)
{
if(num>ans)//找到更大的团,更新答案
{
ans=num;
for(int i=0;i<num;++i)
save[i]=select[i];
}
for(int v=u+1;v<=V;++v)//剪枝:只选择比当前节点编号大的节点,避免重复搜索
{
if(the_max[v]+num<=ans)//A*剪枝,如果继续搜最优情况也不能更新答案
continue;
if(G[u][v])
{
int i;
for(i=0;i<num;++i)
if(!G[v][select[i]])
break;
if(i==num)//和现在团中每个顶点都相邻
{
select[num]=v;
dfs(v,num+1);
}
}
}
}
int main()
{
int T;
scanf("%d",&T);
while(T--)
{
scanf("%d%d",&V,&E);
init();
for(int i=0;i<E;++i)
{
int u,v;
scanf("%d%d",&u,&v);
G[u][v]=G[v][u]=false;
}
for(int u=V;u>0;--u)//不断增大搜索的范围,用于得到估值函数
{
select[0]=u;//添加到当前团中
dfs(u,1);
the_max[u]=ans;//得到估值函数中的一个值
}
printf("%d\n",the_max[1]);
for(int i=0;i<the_max[1];++i)
printf("%d%c",save[i],i==the_max[1]-1?'\n':' ');
}
return 0;
}