Graph Coloring +uva+回溯
2014-07-11 16:10
399 查看
Graph Coloring |
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
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
解决方案:这题和八皇后问题差不多,不多说了直接上代码。
代码:
#include<iostream> #include<cstring> #include<cstdio> #define black 1 #define white 2 using namespace std; int Map[101][101]; int vis[101]; int save[101]; int out[101]; int n,m; int Max; bool judge(int s){ for(int i=1;i<=n;i++){ if(Map[i][s]&&vis[i]==black) return false; } return true; } void dfs(int cur,int s){ if(cur>Max&&s==n+1){ Max=cur; for(int i=0;i<cur;i++){ out[i]=save[i]; } return ; } else if(s==n+1) return ; if(!vis[s]&&judge(s)) { vis[s]=black; save[cur]=s; dfs(cur+1,s+1); vis[s]=0; } if(!vis[s]){ vis[s]=white; dfs(cur,s+1); vis[s]=0; } } int main(){ int t; cin>>t; while(t--){ scanf("%d%d",&n,&m); memset(Map,0,sizeof(Map)); for(int i=0;i<m;i++){ int st,en; scanf("%d%d",&st,&en); Map[st][en]=1; Map[en][st]=1; } memset(vis,false,sizeof(vis)); Max=0; dfs(0,1); cout<<Max<<endl; for(int i=0;i<Max;i++){ printf("%d%c",out[i],i==Max-1?'\n':' '); } } return 0; }
相关文章推荐
- uva - 193 Graph Coloring(回溯)
- uva169 - Graph Coloring (回溯)
- uva 193 Graph Coloring(图染色 dfs回溯)
- UVA - 193 Graph Coloring(回溯)
- uva 193 Graph Coloring(回溯)
- [回溯]Graph Coloring UVA193
- uva 193 Graph Coloring( 图染色 ) DFS+回溯
- UVa 193 - Graph Coloring
- UVA 193 Graph Coloring
- uva 193 Graph Coloring
- UVa 193 & POJ 1419 - Graph Coloring
- uva 193 Graph Coloring
- Uva 193 - Graph Coloring
- UVA 193 - Graph Coloring
- uva 193 - Graph Coloring
- UVa 193 - Graph Coloring
- UVA 193 Graph Coloring 图染色 DFS 数据
- UVA Graph Coloring
- UVa 193 - Graph Coloring
- poj 1419 Graph Coloring uva 193 - Graph Coloring (图着色问题,dfs)