分考场
算法
dfs
题目
题目描述
n个人参加某项特殊考试。
为了公平,要求任何两个认识的人不能分在同一个考场。
求最少需要分几个考场才能满足条件。
输入
第一行,一个整数n(1<n<100),表示参加考试的人数。
第二行,一个整数m,表示接下来有m行数据
以下m行每行的格式为:两个整数a,b,用空格分开 (1<=a,b<=n) 表示第a个人与第b个人认识(编号从1开始)。
输出
一行一个整数,表示最少分几个考场。
样例输入 Copy
5
8
1 2
1 3
1 4
2 3
2 4
2 5
3 4
4 5
样例输出 Copy
4
代码
public class 分考场 {
static int n;
static boolean[][] arr;
static int ans = Integer.MAX_VALUE;
static List<List<Integer>> list = new LinkedList<List<Integer>>();
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
n = sc.nextInt();
int m = sc.nextInt();
arr = new boolean[n+1][n+1];
int a,b;
for(int i=0;i<m;i++){
a = sc.nextInt();
b = sc.nextInt();
arr[a][b]=arr[b][a]=true;
}
dfs(1);
System.out.println(ans);
}
public static void dfs(int now){
if(now == n+1){
ans = Math.min(ans,list.size());
return;
}
if(list.size()>=ans)return;
for(int i=0;i<list.size();i++){
if(check(i,now)){
list.get(i).add(now);
dfs(now+1);
list.get(i).remove(list.get(i).size()-1);
}
}
List<Integer> temp = new LinkedList<>();
temp.add(now);
list.add(temp);
dfs(now+1);
list.remove(list.size()-1);
}
private static boolean check(int index, int now) {
for (int i=0;i<list.get(index).size();i++){
if(arr[list.get(index).get(i)][now]) return false;
}
return true;
}
}