编辑代码

#include <iostream>
#include <algorithm>
#include <list>
#include <vector>
using namespace std;
struct Subject
{
    string SubjectName;
    int start;
    int end;
    Subject(int s, int e, string name)
    {
        start = s;
        end = e;
        SubjectName = name;
    }
};

void printNonIntersectSections(list<Subject>& nonIntersectSections) {
    for (list<Subject>::iterator i = nonIntersectSections.begin(); i != nonIntersectSections.end(); ++i)
    {
        cout << i->start << "," << i->end << "," << i->SubjectName << endl;
    }
    cout << endl;
}
bool compareSectionLength(Subject left, Subject right) {
    return (left.end - left.start) < (right.end - right.start);
}
bool compareSectionStart(Subject left, Subject right) {
    return left.start < right.start;
}
void findNonIntersectSections(vector<Subject>& sections, list<Subject>& nonIntersectSections) {
    sort(sections.begin(), sections.end(), compareSectionStart);
    vector<Subject>::iterator selected = sections.begin();
    while (selected != sections.end())
    {
        int sectionEnd = selected->end;
        vector<Subject>::iterator minEnd = sections.end();
        for (vector<Subject>::iterator i = selected; i != sections.end(); ++i)
        {
            if (nonIntersectSections.size() > 0)
            {
                if (nonIntersectSections.back().end <= i->start && sectionEnd >= i->end)
                {
                    minEnd = i;
                    sectionEnd = i->end;
                }
            }
            else
            {
                if (sectionEnd >= i->end)
                {
                    minEnd = i;
                    sectionEnd = i->end;
                }
            }
        }
        if (minEnd != sections.end())
        {
            selected = minEnd;
            nonIntersectSections.push_back(*selected);
        }
        ++selected;
    }
}
int main()
 {
    vector<Subject> subject;
    subject.push_back(Subject(800, 930, "高数"));
    subject.push_back(Subject(830, 1000, "电子商务"));
    subject.push_back(Subject(930, 1200, "数据结构"));
    subject.push_back(Subject(1000, 1100, "计算机基础"));
    subject.push_back(Subject(1130, 1230, "C语言"));
    list<Subject> nonIntersectSections;
    findNonIntersectSections(subject, nonIntersectSections);
    printNonIntersectSections(nonIntersectSections);
}