【题解】 历届试题 分考场⭐⭐⭐ 【搜索 剪枝】

历届试题 分考场

n个人参加某项特殊考试。
  为了公平,要求任何两个认识的人不能分在同一个考场。
  求是少需要分几个考场才能满足条件。

Input

第一行,一个整数n(1<n<100),表示参加考试的人数。
  第二行,一个整数m,表示接下来有m行数据
  以下m行每行的格式为:两个整数a,b,用空格分开 (1<=a,b<=n) 表示第a个人与第b个人认识。

Output

一行一个整数,表示最少分几个考场。

Examples

样例输入
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

Hint




题意:
题解:

首先构建图, room[i]表示第 i 个房间里的人编号, 搜索房间id和房间数cnt, 注意两点
贪心: 如果有人能放id房间就放, 因为能省就省
剪枝: 当前房间数大于最小答案直接返回
每次有开新房间和放之前的房间两种放法, 注意回溯

经验小结:

多考虑考虑对什么进行搜


#include <cstdio>
#include <iostream>
#include <algorithm>
#include <cstring>
#include <string>
#include <stdlib.h>
#include <vector>
#include <queue>
#include <cmath>
#include <stack>
#include <map>
#include <set>
using namespace std;
#define ms(x, n) memset(x,n,sizeof(x));
typedef  long long LL;
const int inf = 1 << 30;
const LL maxn = 110;

int n, m, ans = inf;
bool G[maxn][maxn];
vector<int> room[maxn];

bool judge(int id, int r){
    for(int i = 0; i < room[r].size(); ++i)
        if(G[room[r][i]][id]) return false;
    return true;
}
void Dfs(int id, int cnt){
   // printf("%d:%d\n",id,cnt);
    if(cnt >= ans) return;   //剪枝
    if(id > n){
        ans = min(cnt, ans);
        return;
    }

    //能否放之前的房间
    for(int i = 1; i <= cnt; ++i){
        if(judge(id, i)){
            room[i].push_back(id);
            Dfs(id+1, cnt);
            room[i].pop_back();
        }
    }
    //放新房间
    room[cnt+1].push_back(id);
    Dfs(id+1, cnt+1);
    room[cnt+1].pop_back();
}
int main() {
    int a, b;
    cin >> n >> m;
    for(int i = 1; i <= m; ++i) {
        cin >> a >> b;
        G[a][b] = G[b][a] = true;
    }

    Dfs(1, 0);
    cout << ans << endl;

    return 0;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值