使用递归函数来确定我们需要多少个教室

时间:2015-11-10 07:54:11

标签: algorithm vba optimization recursion nested-loops

我在VBA中遇到了问题。

在db中有一个 classrooms 表,如

id              limit
--------        ---------
103             35
107             42
109             50
201             45
203             54
204             80
...             ...
..              ..
.               .

还有考试,如下所示

exam_id         participants
--------        ------------
1010            105
1011            320
1012            45
1014            283 
...             ...
..              ..
.               .

我们需要确定最低每次考试需要多少个教室。有些考试只需要一个教室,但有些考试需要十多个教室。因此,我要交叉检查每个教室的容量,以选择最少数量的教室,而不会浪费小型教室。

我一个接一个地参加考试并试图找到一个合适的教室,其中有一个for循环

'all exams
for a=1 to LastExam

 'with all classrooms
 for b=1 to LastClassRoom

  'if it's the first classroom we're checked
  if tempClass = "" then tempClass = b

  'if this classroom capacity is enough for participants
  if examList(a,1) < classRoomList(b,1) then

   'declare it that we found
   findFlag = 1

   'check is it also better than the temp classroom. If it's then
   'mark it as the new temp classroom
   if classRoomList(b,1) < classRoomList(tempClass,1) then
    tempClass = b
   end if
  end if

 next
next

'if we haven't found an enough capacity for it try two nested loops
if findFlag = "" then
 for a1=1 to lastExam-1
  for a2=a1 to lastExam
   ...
    ..
     .

'if two classrooms are not enough try three nested loop
if findFlag = "" then
 for a1=1 to lastExam-2
  for a2=a1 to lastExam-1
   for a3=a2 to lastExam
    ...
     ..
      .


still not found? try four nested loops
...
..
.
five nested loops
...
..
.
till 16 nested loops

嵌套 FOR循环解决方案不合适,因为有16个教室,可能很快就会增加。

我试图创建一个递归函数,但我无法做到。我承认这超出了我的技能范围。我对所有建议持开放态度。谢谢。

1 个答案:

答案 0 :(得分:0)

为什么你需要一个递归解决方案,你可以通过对一个数组进行排序并运行一个for循环来实现它?我认为这可能有所帮助 - &gt;

#include <cstdio>
#include <iostream>
#include <cstdlib>
#include <cmath>
#include <cstring>
#include <map>
#include <set>
#include <vector>
#include <stack>
#include <queue>
#include <algorithm>
#include <string>
#include <sstream>
#include <list>
using namespace std;

int main() {
    int n, k;
    vector< int >hallroom;
    cout<<"How many examHalls ?? :  ";
    cin>>n;
    cout<<"Input ExamHall Capacities : ";
    for(int i=0; i<n; i++)
    {
        int idx;
        cin>>idx;
        hallroom.push_back(idx);
    }
    sort(hallroom.begin(), hallroom.end());
    cout<<"How many examinees ?? :  ";
    cin>>k;
    for(int i=hallroom.size()-1; i>=0; i--)
    {
        k-=hallroom[i];
        if(k<=0)
        {
            cout<<hallroom.size()-i<<endl;
            break;
        }
    }
    return 0;
}