Blue Bridge Cup Practice-Sub-examination room (backtracking recursion)

Blue Bridge Cup practice-sub-examination room (recursive retrospective)
questions:
n individuals take a special exam. In order to be fair, it is required that no two people who know each other can be divided into the same examination room.
At least several examination rooms are required to meet the conditions.
Input format: The  
first line, an integer n (1<n<100), represents the number of people taking the test.

The second line, an integer m, means that there are m lines of data
. The format of each line of the following m lines is: two integers a, b, separated by spaces (1<=a,b<=n), indicating that the ath person and Person b knows.
Output format: 
one integer per line, indicating that there are at least several test rooms.

Idea: This
question is a question that does not seem to be simple, but as long as you have a clear idea of ​​solving the problem, everything is easy to handle. The first easy way to think of is to have n students, starting from number 1 to number n, each student traverses the exam room that has been assigned, if you don’t know one, just join the student in this exam room, if you know, just Switch to the next examination room to judge. If you have knowledge, add a new test room (the initial number of test rooms is 0). After all the students are arranged, if you see if it is the minimum value, go back and look for it.
One must think of pruning , otherwise it will time out . In the backtracking process, as long as the ratio is greater than or equal to the minimum value, it returns directly and continues another arrangement.
Then, for the convenience of programming, select the appropriate data structure. Here, the examination room uses the vector variable length array in the STL library in C++ to facilitate the addition and deletion of student ids in the examination room.

#include <iostream>
#include <vector>
#include <algorithm>
#define inf 999999
using namespace std;
int n,m,minclassroom=inf;
int stumap[101][101]={
    
    0};
vector <int> room[101];
void dfs(int id,int roomnum)
{
    
    
 int i,j;
 if(roomnum>=minclassroom)
 {
    
    
  return;
 }
 if(id==n+1)
 {
    
    
  minclassroom=(minclassroom,roomnum);
  return;
 }
 for(i=1;i<=roomnum;i++)
 {
    
    
  int flag=1;
  for(j=0;j<room[i].size();j++)
  {
    
    
   if(stumap[room[i][j]][id]==1)
   {
    
    
    flag=0;
    break;
   }
  }
  if(flag==1)
     {
    
    
  room[i].push_back(id);
  dfs(id+1,roomnum);
  vector<int>::iterator it=room[i].end();
  it--;
  room[i].erase(it);
  }
 }
 room[roomnum+1].push_back(id);
 dfs(id+1,roomnum+1);
 vector<int>::iterator it=room[i].end();
 it--;
 room[roomnum+1].erase(it);
 return;
}
int main()
{
    
    
 int a,b,i;
 cin>>n>>m;
 for(i=1;i<=m;i++)
 {
    
    
  cin>>a>>b;
  stumap[a][b]=1;
  stumap[b][a]=1;
 }
 dfs(1,0);
 cout<<minclassroom<<endl;
 return 0;
} 

Guess you like

Origin blog.csdn.net/HT24k/article/details/107255700