Graph Coloring
| Time Limit: 1000MS | Memory Limit: 10000K | |||
| Total 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
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
题意:给一个图让你给节点上黑白色,要求黑色的点不能相邻,问最多能涂几个黑色点。思路:实际就是求最大独立集,即子图上点两两不相连的最大集,就是求补图的最大团。
# 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;
}
本文探讨了图论中的一个经典问题——图染色问题,旨在寻找最优的节点染色方案,使得相邻节点颜色不同且黑色节点数量最多。通过递归深度优先搜索策略实现了最大独立集的求解。
164

被折叠的 条评论
为什么被折叠?



