POJ-1129 Channel Allocation

题意:给定无向图,对点着色,使得相邻的结点颜色不同。

思路:直接dfs爆搜即可

Sample Input

2
A:
B:
4
A:BC
B:ACD
C:ABD
D:BC
4
A:BCD
B:ACD
C:ABD
D:ABC
0

Sample Output

1 channel needed.
3 channels needed.
4 channels needed.
 1 import java.util.Arrays;
 2 import java.util.Scanner;
 3 
 4 public class Main1129 {
 5     static int map[][];
 6     static int temp[],max=1;
 7     static int n;
 8     static boolean bool;
 9     public static void main(String args[])
10     {
11         Scanner sc=new Scanner(System.in);
12         n=sc.nextInt();
13         while(n!=0)//读入图
14         {
15         map=new int[n][n];
16         temp=new int[n];
17         for(int i=0;i<n;i++)
18         {
19             String s=sc.next();
20             s=s.substring(2);
21             for(int j=0;j<s.length();j++)
22                 map[i][s.charAt(j)-65]=1;
23            
24         }
25         
26         dfs(0,1);
27         if(max==1)
28             System.out.println(max+" channel needed.");
29         else
30             System.out.println(max+" channels needed.");
31         max=1;
32         bool=false;
33         n=sc.nextInt();
34         }
35         
36     }
37     public static void dfs(int t,int kind)//点,颜色种类
38     {
39             if(t>=n)
40             {
41                 bool=true;
42             }
43         
44             else
45             {
46                 for(int i=1;i<=kind;i++)
47                 {
48                     if(Bound(t,i))//点t是否可以涂颜色i
49                     {
50                         temp[t]=i;
51                         dfs(t+1,kind);    
52                     }
53                 }
54                 if(!bool)//如果目前所有颜色行不通就加一种新颜色
55                 {
56                     max++;
57                     dfs(t,kind+1);
58                 }
59             }
60     }
61     public static boolean Bound(int t,int c)
62     {
63         for(int i=0;i<n;i++)
64             if(map[t][i]==1&&c==temp[i])
65                 return false;
66         return true;
67     }
68 }
View Code

猜你喜欢

转载自www.cnblogs.com/gdskl/p/11445885.html