24h購物| | PChome| 登入
2012-02-29 12:15:51| 人氣2,904| 回應1 | 上一篇 | 下一篇

[UVA] 193 - Graph Coloring

推薦 0 收藏 0 轉貼0 訂閱站台

 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.

  figure22
Figure: An optimal graph with three black nodes

Input and Output

The graph is given as a set of nodes denoted by numbers tex2html_wrap_inline33 , tex2html_wrap_inline35 , and a set of undirected edges denoted by pairs of node numbers tex2html_wrap_inline37 , tex2html_wrap_inline39 . 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;
}

台長: Morris
人氣(2,904) | 回應(1)| 推薦 (0)| 收藏 (0)| 轉寄
全站分類: 不分類 | 個人分類: UVA |
此分類下一篇:[UVA] 1099 - Sharing Chocolate
此分類上一篇:[UVA] 11456 - Trainsorting

xem phim online
nice article...
2017-10-03 14:10:55
是 (若未登入"個人新聞台帳號"則看不到回覆唷!)
* 請輸入識別碼:
請輸入圖片中算式的結果(可能為0) 
(有*為必填)
TOP
詳全文