教室規劃問題

來源:互聯網
上載者:User

//某大學有n門課程要使用同一間教室上課,設計一個演算法找出容納盡量多的課程上課
//使用貪婪演算法
#include<iostream>
#include<vector>
#include<algorithm>

using namespace std;

const int n=12; //課程總數

typedef struct
{
 int i; //課程式號
 int s; //課程開始時間
 int f; //課程結束時間
}Course;

class LessThan
{
public:
 bool operator()(const Course& c1,const Course& c2)
 {
  int a,b;
  a=c1.f-c1.s; //課程完成時間
  b=c2.f-c2.s;
  return a<=b;
 }
};
 
//檢查兩門課程排課時間是不是衝突,如果不衝突,函數返回真
bool Compatability(const Course& c1,const Course& c2)
{
 if(c1.f<=c2.s || c2.f<=c1.s) return true;
 else return false;
}

void CouseScheduler(const vector<Course>&c,vector<Course>&maxCourse)
{
 vector<Course>::const_iterator it=c.begin();
 maxCourse.push_back(*it); //將排序好的第一門課程加入最大相容課程集合
 it++;
 while(it!=c.end())
 {
  vector<Course>::const_iterator it1;
  for(it1=maxCourse.begin();it1!=maxCourse.end();it1++) //檢查it所指的課程和最大相容課程集合是不是存在衝突
  {
   if(!Compatability(*it1,*it)) break;
  }
  if(it1==maxCourse.end()) maxCourse.push_back(*it);
  *it++;
 }
}

void main()
{
 vector<Course>c;
 int i;
 Course course;
 for(i=0;i<n;i++) //檢查輸入合法性
 {
  cout<<"請輸入第"<<i+1<<"門課程的開始時間:";
  course.i=i+1;
  cin>>course.s;
  if(!cin.good())
  {
   throw runtime_error("輸入異常!");
  }
  if(course.s<0)
  {
   cerr<<"輸入應該大於等於0的數!"<<endl;
   course.s=0;
   i--;
   continue;
  }
  cout<<"請輸入第"<<i+1<<"門課程的結束時間:";
  cin>>course.f;
  if(!cin.good())
  {
   throw runtime_error("輸入異常!");
  }
  if(course.f<0)
  {
   cerr<<"輸入應該大於等於0的數!"<<endl;
   course.f=0;
   i--;
   continue;
  }
  if(course.f<=course.s)
  {
   cerr<<"結束時間應該大於開始時間!"<<endl;
   i--;
   continue;
  }
  c.push_back(course);
 }
 sort(c.begin(),c.end(),LessThan()); //按照課程完成時間對所有課程排序
 vector<Course>::const_iterator it;
 for(it=c.begin();it!=c.end();it++)
 {
  cout<<"課程編號:"<<it->i<<endl;
  cout<<"開始時間是:"<<it->s<<endl;
  cout<<"結束時間是:"<<it->f<<endl;
  cout<<"課程完成時間是:"<<it->f-it->s<<endl;
 }
 vector<Course>maxCourse;
 CouseScheduler(c,maxCourse);
 cout<<"最大相容課程集合是:"<<endl;
 for(it=maxCourse.begin();it!=maxCourse.end();it++)
 {
  cout<<"課程編號:"<<it->i<<endl;
  cout<<"開始時間是:"<<it->s<<endl;
  cout<<"結束時間是:"<<it->f<<endl;
  cout<<"課程完成時間是:"<<it->f-it->s<<endl;
 }
}

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.