java蓝桥杯练习 分考场
资源限制
时间限制:1.0s 内存限制:256.0MB
问题描述
n个人参加某项特殊考试。
为了公平,要求任何两个认识的人不能分在同一个考场。
求是少需要分几个考场才能满足条件。
输入格式
第一行,一个整数n(1<n<100),表示参加考试的人数。
第二行,一个整数m,表示接下来有m行数据
以下m行每行的格式为:两个整数a,b,用空格分开 (1<=a,b<=n) 表示第a个人与第b个人认识。
输出格式
一行一个整数,表示最少分几个考场。
样例输入
5
8
1 2
1 3
1 4
2 3
2 4
2 5
3 4
4 5
样例输出
4
样例输入
5
10
1 2
1 3
1 4
1 5
2 3
2 4
2 5
3 4
3 5
4 5
样例输出
5
//java code
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int n = sc.nextInt();
int m = sc.nextInt();
int shu[][]=new int[n][n];
for (int i = 0; i < m; i++) {
int a=sc.nextInt()-1;
int b=sc.nextInt()-1;
shu[a][b]=1;
shu[b][a]=1;
}
sc.close();
int res=solve(shu);
System.out.println(res);
}
static int solve(int shu[][]){
for (int i = 1; i <= shu.length; i++) {
if(check(shu,i))
return i;
}
return shu.length;
}
static boolean check(int shu[][],int i){
int boo[]=new int[shu.length];
boo[0]=1;
return step(shu,boo,1,1,i);
}
static boolean step(int shu[][],int boo[],int x,int y,int z){
if(y>z) return false;
if(x>=shu.length) return true;
for (int i = 1; i <= y; i++) {
boo[x]=i;
if(re_back(shu,boo,x)&&step(shu,boo,x+1,y,z)) return true;
boo[x]=0;
}
boo[x]=y+1;
if(step(shu,boo,x+1,y+1,z)) return true;
boo[x]=0;
return false;
}
static boolean re_back(int shu[][],int boo[],int x){
for (int i = 0; i < shu.length; i++) {
if(x==i) continue;
if(shu[x][i]==1&&boo[i]==boo[x]) return false;
}
return true;
}
}