蓝桥杯 分考场

问题描述
  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
AC的C++程序如下:

#include<iostream>
#include<cstring>
#include<string>
#include<algorithm>
using namespace std;
const int maxn=105;
const int inf=0x3f3f3f3f;
int n,m;
int a[maxn][maxn],room[maxn];//记录每个房间的人数 
int no[maxn][maxn];//记录第i个房间的第j个人的编号 
int ans=inf;//记录最小的房间数 
void dfs(int num,int x) //判断第x个人,当前已经用了num个房间 
{	
     if(num>=ans) return; //剪枝 
	 if(x==n+1) //如果遍历完了则结束 
	 {
	 	ans=min(num,ans);
	 	return;
	 }
	 for(int i=1;i<=num;i++) //遍历每个房间 
	 {
	 	int sum=room[i];
	 	int count=0;//记录可以在一个房间人的总数 
	 	for(int j=1;j<=sum;j++)
	 	{
	 		if(a[x][no[i][j]]==0) count++;//可以在一个房间
		
		 }
		  if(count==sum) //如果和每个人都不认识 
			 {
			 	no[i][++room[i]]=x;
			 	dfs(num,x+1);
			 	--room[i];
			  } 
	  } 
	  no[num+1][++room[num+1]]=x;//新开一个房间 
	  dfs(num+1,x+1);
	  --room[num+1];
}
int main()
{
	cin>>n>>m;
	memset(a,0,sizeof(a));
    for(int i=1;i<=m;i++)
    {
    	int u,v;
    	cin>>u>>v;
    	a[u][v]=1;
    	a[v][u]=1;
	}
	dfs(0,1);
	cout<<ans<<endl;
 } 

猜你喜欢

转载自blog.csdn.net/jinduo16/article/details/86722379