首页 > 代码库 > uva193 - Graph Coloring
uva193 - Graph Coloring
Graph Coloring
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: An optimal graph with three black nodes
Input and Output
The graph is given as a set of nodes denoted by numbers , , and a set of undirected edges denoted by pairs of node numbers , . 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.
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
求图的最大独立集,即把尽量多的结点图黑使得任意两个黑点不相邻
#include<cstdio>#include<cstring>#include<iostream>#include<vector>#include<algorithm>using namespace std;const int maxn=100+5;int m,n,k;vector<int> G[maxn];int node[maxn], black_node[maxn];int ans;enum {white, black};void dfs(int d, int cnt) { if(d==n) { if(cnt>ans) { int j=0; for(int i=0;i<n;i++) if(node[i]) black_node[j++]=i+1; ans=cnt; } return; } if(n-d+cnt<=ans) return; //尝试黑的 int ok=true; node[d]=black; for(int i=0;i<G[d].size();i++) { int v=G[d][i]; //两个相邻黑点 if(node[v]==black) { ok=false; break; } } if(ok) dfs(d+1, cnt+1); //尝试白的 node[d]=white; dfs(d+1, cnt);}int main(){#ifndef ONLINE_JUDGE freopen("./uva193.in", "r", stdin);#endif int x,y; cin>>m; while(m--) { cin>>n>>k; memset(G, 0, sizeof(G)); memset(node, 0, sizeof(node)); ans=0; for(int i=0;i<k;i++) { cin>>x>>y; x--;y--; G[x].push_back(y); G[y].push_back(x); } dfs(0, 0); printf("%d\n", ans); for(int i=0;i<ans-1;i++) printf("%d ", black_node[i]); printf("%d\n", black_node[ans-1]); } return 0;}