zoukankan      html  css  js  c++  java
  • 分考场(np完全问题,回溯法)

    问题描述
      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
    基本思路:
    回溯啊,一开始疯了没剪枝,后来想剪枝的时候发现想不到什么剪枝策略,就很难受,然后就加了一个最显而易见的剪枝就过了
    代码如下:
    #include<iostream>
    #include<string>
    #include<algorithm>
    #include<cstdio>
    #include<cstring>
    #include<cmath>
    #include<vector>
    
    using namespace std;
    
    const int maxn = 110;
    const int inf = 0x3f3f3f3f;
    int gra[maxn][maxn];
    int cun[maxn][maxn];
    int cnt[maxn];
    int res=inf;
    int n,m;
    void solve(int id,int num){
        if(num>=res){
            return;
        }
        if(id>n){
            res=min(res,num);
            return;
        }
        for(int i=1;i<=num;i++){
            int sz=cnt[i];
            int jishu=0;
            for(int j=1;j<=sz;j++){
                if(gra[id][cun[i][j]]==0){
                    jishu++;
                }
            }
            if(jishu==sz){
                cun[i][++cnt[i]]=id;
                solve(id+1,num);
                cnt[i]--;
            }
        }
        cun[num+1][++cnt[num+1]]=id;
        solve(id+1,num+1);
        --cnt[num+1];
    }
    int main(){
        scanf("%d%d",&n,&m);
        memset(gra,0,sizeof(gra));
        memset(cnt,0,sizeof(cnt));
        while(m--){
            int a,b;
            scanf("%d%d",&a,&b);
            gra[a][b]=gra[b][a]=1;
        }
        solve(1,0);
        printf("%d
    ",res);
        return 0;
    }
    

      

  • 相关阅读:
    NOI 2020 游记
    BJOI2020 游记
    行列式
    CSP-S 2019 游记
    类欧几里得算法
    有关二次离线和 Yuno loves sqrt technology II
    NOI2019 游记
    CTS 2019 Pearl
    BJOI2019 游记
    2017 山东二轮集训 Day7 国王
  • 原文地址:https://www.cnblogs.com/imzscilovecode/p/8649540.html
Copyright © 2011-2022 走看看