poj 1129 Channel Allocation

时间:2023-11-29 14:56:32

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

 import java.util.*;
import java.math.*;
public class Main {
public static boolean flag=false;
public static int ans=0;
public static void main(String []args)
{
Scanner cin=new Scanner(System.in);
int n;
String str;
while(cin.hasNext())
{
ans=1;
int [][]g=new int[100][100];
int []hash=new int[100];
n=cin.nextInt();
if(n==0) break;
for(int i=0; i<n; i++)
{
str=cin.next();
for(int j=2; j<(int)str.length(); j++)
{
g[str.charAt(0)-'A'][str.charAt(j)-'A']=1;
}
}
flag=false;
dfs(0,1,g,n,hash);
if(ans==1)
{
System.out.println("1 channel needed.");
}
else
{
System.out.println(ans+" channels needed.");
}
}
}
public static int deal(int id,int co,int n,int g[][],int hash[])
{
for(int i=0; i<n; i++)
{
if(g[id][i]==1&&co==hash[i])
{
return 0;
}
}
return 1;
}
public static void dfs(int num,int m1,int g[][],int n,int hash[])
{
if(flag) return;
if(num>=n)
{
flag=true;
return;
}
for(int i=1; i<=m1; i++)
{
if(deal(num,i,n,g,hash)==1)
{
hash[num]=i;
dfs(num+1,m1,g,n,hash);
hash[num]=0;
}
}
if(flag==false)
{
ans++;
dfs(num,m1+1,g,n,hash);
}
}
}