(蓝桥杯)分考场(无向图染色)

题目链接:点击打开链接

问题描述
  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

题目思路:

    可以抽象为无向图染色问题。相邻顶点不能染相同颜色,问至少要用多少种颜色。

    用DFS搜搜搜。

#include<iostream>
#include<cstdio>
#include<cstring>
#include<algorithm>
#include<vector>

using namespace std;

const int inf = 0x3f3f3f3f;
const int maxn = 1005;
int n,m,ans=inf,tot;
int a[maxn][maxn],c[maxn],f[maxn][maxn]; //f表示第i个屋子里的第j个人的编号 
bool vis[maxn];

void dfs(int x,int tot) //x表示当前判断的是第x个同学,tot表示已经用掉的屋子个数
{
	if(tot>=ans) 	//剪枝
		return;
	if(x==n+1) { //如果已经搜完了n个人,进行判断
		ans = min(ans,tot);
		return;
	}	
	for(int i=1;i<=tot;i++) //对已有的屋子进行遍历
	{
		int len = c[i]; //c[i]表示第i个屋子里面的人数
		int k = 0;
		for(int j=1;j<=len;j++)
		{
			if(!a[x][f[i][j]])  //如果这两个人没有关联,k++
				k++;
		}
		if(k==len)  //如果这个屋子里所有人都与x没有关联,那么就把x放进这个屋子里
		{
			f[i][++c[i]] = x; //++c[i]表示第i个屋子里的人数+1,f数组表示这个人的编号
			dfs(x+1,tot); //继续深搜
			c[i]--; //回溯
		}
	}
	f[tot+1][++c[tot+1]] = x;  //如果所有房间都不满足条件,只能新开个房间放
	dfs(x+1,tot+1);
	c[tot+1]--; //回溯
}

int main()
{
	scanf("%d%d",&n,&m);
	for(int i=0;i<m;i++)
	{
		int x,y;
		scanf("%d%d",&x,&y);
		a[x][y] = a[y][x] = 1;
	}
	dfs(1,0);
	cout<<ans<<endl;
	return 0;
}

猜你喜欢

转载自blog.csdn.net/zxwsbg/article/details/80376847