这个主要是对边界条件的处理需要注意,比如只有一个会议,两个会议以及重叠与不重叠各种情况。
cpp
#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;
struct MeetingTime {
int start;
int end;
};
bool compare(const MeetingTime &a, const MeetingTime &b) {
return a.start < b.start;
}
int main() {
int meeting_num = 0;
cin >> meeting_num;
vector<MeetingTime> meetings;
for (int i = 0; i < meeting_num; i++)
{
MeetingTime a;
cin >> a.start >> a.end;
meetings.push_back(a);
}
// 假设已经通过某种方式填充了meetings向量
// 例如:meetings = {{1, 4}, {2, 5}, {7, 9}, {14, 18}};
// 排序
sort(meetings.begin(), meetings.end(), compare);
// 合并时间段
vector<MeetingTime> merged;
int meetings_num = meetings.size();
for (int i = 0; i < meetings_num; ++i) {
//如果只有一个会议 直接输出
if(meetings.size() == 1)
{
merged.push_back(meetings[i]);
}
//如果当前会议时间和后面一个会议重叠 则需要将两次会议合并 直接将合并后的会议替换下一个会议时间
else if (meetings[i].end >= meetings[i + 1].start && i<meetings_num-1)
{
MeetingTime curr = meetings[i];
if (meetings[i].end < meetings[i + 1].end) {
curr.end = meetings[i + 1].end;
}
meetings[i + 1].start = curr.start;
meetings[i + 1].end = curr.end;
}
else
{
//如果是倒数第二个会议 需要单独处理
if(i == meetings.size()-2)
{
//如果与最后一个会议不重叠 则将当前会议输出
if(meetings[i].end < meetings[i + 1].start)
{
merged.push_back(meetings[i]);
//merged.push_back(meetings[i+1]);
}
else if(meetings[i].end >= meetings[i + 1].start)
{
MeetingTime curr = meetings[i];
if (meetings[i].end < meetings[i + 1].end) {
curr.end = meetings[i + 1].end;
}
merged.push_back(curr);
}
}
else
{
merged.push_back(meetings[i]);
}
}
}
// 输出结果
for (const auto &m : merged) {
cout << m.start << " " << m.end << endl;
}
return 0;
}