procedure2012
It's not worth it to know you're not worth it!

[题目来源]:POJ1129

[关键字]:搜索

[题目大意]:给出一个平面图对其染色,有边相连的点不能染相同颜色,问最少需多少颜色。

//============================================================================================================

[分析]:著名的四色染色问题:对一个完全图有边相连的点不能染相同颜色最多四种颜色就可完成染色。所以搜索每个点染什么色,dfs就行。我做时对于每个点可以染什么色的限制和还原现场做得有点不好,WA好几次。

[代码]:

View Code
 1 program Project1;
2 var
3 n, ans: longint;
4 w1, w2, w: string;
5 c: array[0..30] of 0..10;
6 b, t: array[0..30,1..10] of boolean;
7 a: array[0..30,0..30] of boolean;
8 f: array[0..10] of boolean;
9
10 procedure init;
11 var
12 i, j, x, y: longint;
13 s: string;
14 begin
15 readln(n);
16 if n = 0 then halt;
17 fillchar(a,sizeof(a),false);
18 for i := 1 to n do
19 begin
20 readln(s);
21 x := ord(s[1])-64;
22 delete(s,1,2);
23 for j := 1 to length(s) do
24 begin
25 y := ord(s[j])-64;
26 a[x,y] := true;
27 end;
28 end;
29 fillchar(c,sizeof(c),0);
30 fillchar(b,sizeof(b),true);
31 fillchar(f,sizeof(f),false);
32 end;
33
34 procedure dfs(k: longint);
35 var
36 i, j, now: longint;
37 flag: boolean;
38 begin
39 if k > n then
40 begin
41 now := 0;
42 for i := 1 to 4 do
43 if f[i] then inc(now);
44 if now < ans then ans := now;
45 exit;
46 end;
47 for i := 1 to 4 do
48 if b[k,i] then
49 begin
50 c[k] := i;
51 flag := f[i];
52 f[i] := true;
53 for j := 1 to n do
54 if a[k,j] then
55 begin
56 t[j,i] := b[j,i];
57 b[j,i] :=false;
58 end;
59 dfs(k+1);
60 for j := 1 to n do
61 if a[k,j] then
62 b[j,i] := t[j,i];
63 f[i] := flag;
64 end;
65 end;
66
67 procedure print;
68 begin
69 w := '';
70 if ans >= 2 then w := w1+'s'+w2 else w := w1+w2;
71 writeln(ans,w);
72 end;
73
74 begin
75 w1 := ' channel';
76 w2 := ' needed.';
77 while 1 = 1 do
78 begin
79 init;
80 ans := 10;
81 dfs(1);
82 print;
83 end;
84 end.

posted on 2011-10-19 16:56  procedure2012  阅读(227)  评论(0编辑  收藏  举报