POJ1419:Graph Coloring(图的最大独立集)

来源:互联网 发布:学计算机编程需要多久 编辑:程序博客网 时间:2024/06/01 07:53

Graph Coloring
Time Limit: 1000MS Memory Limit: 10000KTotal Submissions: 5260 Accepted: 2447 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 

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

16 81 21 32 42 53 43 64 65 6

Sample Output

31 4 5

Source

Southwestern European Regional Contest 1995
题意:给一个图让你给节点上黑白色,要求黑色的点不能相邻,问最多能涂几个黑色点。

思路:实际就是求最大独立集,即子图上点两两不相连的最大集,就是求补图的最大团。

# include <iostream># include <cstdio># include <cstring>using namespace std;int g[103][103], ans[103], tmp[103], dp[103], a[103][103];int n, m, imax, _;void dfs(int up, int dep){    if(up == 0)    {        if(dep > imax)        {            imax = dep;            for(int i=0; i<_; ++i)                ans[i] = tmp[i];        }        return;    }    for(int i=0; i<up; ++i)    {        int u = a[dep][i];        if(dep + n - u + 1 <= imax) return;        if(dep + dp[u] <= imax) return;        tmp[_++] = u;        int cnt = 0;        for(int j=i+1; j<up; ++j)        {            int v = a[dep][j];            if(!g[u][v]) a[dep+1][cnt++] = v;        }        dfs(cnt, dep+1);        --_;    }}void solve(){    for(int i=n; i>=1; --i)    {        int cnt = 0;        _ = 0;        tmp[_++] = i;        for(int j=i+1; j<=n; ++j)            if(!g[i][j]) a[1][cnt++] = j;        dfs(cnt, 1);        dp[i] = imax;    }    printf("%d\n",imax);    for(int i=0; i<imax; ++i)        printf("%d ",ans[i]);}int main(){    int t;    scanf("%d",&t);    while(t--)    {        imax = _ = 0;        scanf("%d%d",&n,&m);        memset(g, 0, sizeof(g));        memset(dp, 0, sizeof(dp));        for(int i=0; i<m; ++i)        {            int x, y;            scanf("%d%d",&x,&y);            g[x][y] = g[y][x] = 1;        }        solve();    }    return 0;}