藍橋杯算法題解 歷屆試題 分考場

題目描述

問題描述
  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

題解:

直接看代碼的註釋。
**注意: **必須要有剪枝,否則只有40分。

代碼:

#include <iostream>
#include <cstdio>
#include <cstdlib>
#include <cmath>
#include <climits>
#include <cstring>
#include <string>
#include <algorithm>
#include <vector>
#include <deque>
#include <list>
#include <utility>
#include <set>
#include <map>
#include <stack>
#include <queue>
#include <bitset>
#include <iterator>
using namespace std;

typedef long long ll;
const int inf = 0x3f3f3f3f;
const ll  INF = 0x3f3f3f3f3f3f3f3f;
const double PI = acos(-1.0);
const double E = exp(1.0);
const int MOD = 1e9+7;
const int MAX = 1e2+5;

int n,m;
int a,b;
int stuMap[MAX][MAX] = {0};// 學生之間的映射關係(stuMap[i][j]=1or0)
vector <int> room[MAX];// room[i].size:表示考場i的已有學生人數,room[i][j]:表示考場i的第j個學生
int minRoomNum = inf;// 最少的考場數量

void func(int id,int roomNum)// id:正在安排的學生編號,roomNum:已經分配的考場數量
{
    //printf("學生編號: %d,考場已分配的數量: %d\n",id,roomNum);
    if(roomNum >= minRoomNum)
    {
        // 剪枝:如果已經分配的考場數量大於了當前可以分配的最少考場數量,說明沒有必要繼續進行遞歸了
        return;
    }
    if(id == n+1)
    {
        // 當已經分配了n個學生了,就記錄最少的考場數量
        minRoomNum = min(minRoomNum,roomNum);
        return;
    }
    // 此時需要爲第id個學生分配教室,要滿足條件:不跟分配的教室的任何一個人認識
    // 如果滿足,直接分配到這個考場room[i].push_back(id);
    // 如果不滿足,說明需要重新開一個考場,room[roomNum+1].push_back(id);
    for(int i = 1; i <= roomNum; i++)
    {
        bool flag = true;
        for(int j = 0; j < room[i].size(); j++)
        {
            if(stuMap[id][room[i][j]] == 1)
            {
                flag = false;
                break;
            }
        }
        if(flag)// 對於學生id,不認識考場i的任何一個人,可以直接分配到這個考場
        {
            room[i].push_back(id);
            func(id+1,roomNum);
            // 回溯:將這個學生拿出這個考場,重新分配
            vector<int>::iterator tmp = room[i].end(); tmp--;
            room[i].erase(tmp);
        }
    }
    // 如果前面沒有回溯進去,說明學生id和roomNum個考場都有認識的人,要重新開個考場
    room[roomNum+1].push_back(id);
    func(id+1,roomNum+1);
    vector<int>::iterator tmp = room[roomNum+1].end(); tmp--;
    room[roomNum+1].erase(tmp);
}

int main()
{
    /*
    ios::sync_with_stdio(false);
    cin.tie(0);
    cout.tie(0);
    */
    cin >> n >> m;
    for(int i = 1; i <= m; i++)
    {
        cin >> a >> b;
        stuMap[a][b] = stuMap[b][a] = 1;
    }
    func(1,0);// 從第一個學生開始安排,此時沒有分配教室
    cout << minRoomNum << endl;

    return 0;
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章