//某大學有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;
}
}