標籤:des style blog http color os io strong
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;}