poj 1129 Channel Allocation

http://poj.org/problem?id=1129

 1 import java.util.*;

 2 import java.math.*;

 3 public class Main {

 4     public static boolean flag=false;

 5     public static int ans=0;

 6     public static void main(String []args)

 7     {

 8         Scanner cin=new Scanner(System.in);

 9         int n;

10         String str;

11         while(cin.hasNext())

12         {

13             ans=1;

14             int [][]g=new int[100][100];

15             int []hash=new int[100];

16              n=cin.nextInt();

17              if(n==0) break;

18              for(int i=0; i<n; i++)

19              {

20                  str=cin.next();

21                  for(int j=2; j<(int)str.length(); j++)

22                  {

23                      g[str.charAt(0)-'A'][str.charAt(j)-'A']=1;

24                  }

25              }

26              flag=false;

27              dfs(0,1,g,n,hash);

28              if(ans==1)

29              {

30              System.out.println("1 channel needed.");

31              }

32              else

33              {

34                  System.out.println(ans+" channels needed.");

35              }

36         }

37     }

38     public static int deal(int id,int co,int n,int g[][],int hash[])

39     {

40         for(int i=0; i<n; i++)

41         {

42             if(g[id][i]==1&&co==hash[i])

43             {

44                 return 0;

45             }

46         }

47         return 1;

48     }

49     public static void dfs(int num,int m1,int g[][],int n,int hash[])

50     {

51         if(flag) return;

52         if(num>=n)

53         {

54             flag=true;

55             return;

56         }

57         for(int i=1; i<=m1; i++)

58         {

59             if(deal(num,i,n,g,hash)==1)

60             {

61                 hash[num]=i;

62                 dfs(num+1,m1,g,n,hash);

63                 hash[num]=0;

64             }

65         }

66         if(flag==false)

67         {

68             ans++;

69             dfs(num,m1+1,g,n,hash);

70         }

71     }

72 }
View Code

 

你可能感兴趣的:(location)