0
点赞
收藏
分享

微信扫一扫

POJ - 1419  Graph Coloring(最大团+输出路径模板)


Graph Coloring

 ​​POJ - 1419 ​​

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 8 1 2 1 3 2 4 2 5 3 4 3 6 4 6 5 6


Sample Output


31 4 5


 题意:

给出你一个无向图,然后对其中的点去上色, 只能上黑色和白色,要求是黑色点不能相邻(白色可以相邻),问最多能上多少黑色的顶点。

题解:

无向图最大独立子集问题,无向图的最大独立子集=补图的最大团。

因为这题要输出点,直接套最大团的个数。

#include <cstdio>
#include <cstring>
using namespace std;
const int N = 102;
int n, ans, cnt, vis[N], opt[N];
bool map[N][N];

void dfs(int i) {
if (i > n) {
ans = cnt;
for (int i = 1; i <= n; i++) opt[i] = vis[i];
return;
}
bool flag = true;
for (int j = 1; j < i && flag; j++)
if (vis[j] == 1 && !map[j][i]) flag = false;
if (flag) {
vis[i] = 1;
cnt++;
dfs(i + 1);
cnt--;
}
if (cnt + n - i > ans) {//可行性剪枝,只有剩下为的节点大于前面状态
vis[i] = 0;
dfs(i + 1);
}
}

int main() {
int T, m, x, y;
scanf("%d", &T);
while (T--)
{
scanf("%d%d", &n, &m);
memset(map, 1, sizeof(map)); //反图注意初始化为1

for (int i = 1; i <= m; i++) {
scanf("%d%d", &x, &y);
map[x][y] = map[y][x] = 0; //反图
}
ans = cnt = 0;
dfs(1); //求反图最大团

printf("%d\n", ans);
for (int i = 1; i <= n; i++)
if (opt[i]) printf("%d ", i);
printf("\n");
}
return 0;
}

 

 

举报

相关推荐

0 条评论