[UVA] 193 - Graph Coloring
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
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 <stdio.h>
#include <string.h>
int map[101][101], mt[101];
int tmp[101], Ans[101], maxL;
int cant[101];
int T, n, m;
void DFS(int node, int choose, int notchoose) {
if(choose + notchoose == n || node == n+1) {
if(choose > maxL) {
maxL = choose;
int i;
for(i = 0; i < maxL; i++)
Ans[i] = tmp[i];
}
return;
}
if(cant[node] == 0) {
int i, newNot = notchoose;
int reduce[n], idx = 0;
for(i = 0; i < mt[node]; i++) {
if(cant[map[node][i]] == 0) {
cant[map[node][i]] = 1, newNot++;
reduce[idx++] = map[node][i];
}
}
tmp[choose] = node;
DFS(node+1, choose+1, newNot);
for(i = 0; i < idx; i++)
cant[reduce[i]] = 0;
}
DFS(node+1, choose, notchoose+(!cant[node]));
}
int main() {
int i, x, y;
scanf("%d", &T);
while(T--) {
scanf("%d %d", &n, &m);
memset(mt, 0, sizeof(mt));
memset(cant, 0, sizeof(mt));
for(i = 0; i < m; i++) {
scanf("%d %d", &x, &y);
map[x][mt[x]++] = y;
map[y][mt[y]++] = x;
}
maxL = 0;
DFS(1, 0, 0);
printf("%d\n", maxL);
for(i = 0; i < maxL-1; i++)
printf("%d ", Ans[i]);
printf("%d\n", Ans[i]);
}
return 0;
}
nice article...