题目
现有若干个会议,所有会议共享一个会议室,用数组表示每个会议的开始时间和结束时间,格式:[[会议1开始时间,会议1结束时间], [会议2开始时间,会议2结束时间]]。请计算会议室占用时间段。
输入
第一行输入一个整数n,表示会议数量
之后输入n行,每行两个整数,以空格分隔,分别表示会议开始时间,会议结束时间
输出
输出多行,每个两个整数,以空格分隔,分别表示会议室占用时间段开始和结束
样例输入 复制
4
1 4
2 5
7 9
14 18
样例输出 复制
1 5
7 9
14 18
补充提示
输入:[[1,4],[2,5],[7,9],[14,18]]
输出:[[1,5],[7,9],[14,18]]
说明:时间段[1,4]和[2,5]重叠,合并为[1,5]
#include <stdio.h>
#include <map>
#include <vector>
#include <iostream>
#include <string>
#include <algorithm>
#include <math.h>
using namespace std;
class CMeetTime
{
public:
CMeetTime()
:m_uiTimeStart(0),m_uiTimeEnd(0),m_bEnable(false)
{
}
CMeetTime(unsigned int uiStart,unsigned int uiEnd)
:m_uiTimeStart(0),m_uiTimeEnd(0),m_bEnable(false)
{
if (uiStart < uiEnd)
{
m_uiTimeStart = uiStart;
m_uiTimeEnd = uiEnd;
m_bEnable = true;
}
}
bool MergeMeetTime(CMeetTime& oMeetTime)
{
if (m_bEnable && oMeetTime.m_bEnable)
{
if (m_uiTimeStart <= oMeetTime.m_uiTimeStart && oMeetTime.m_uiTimeStart <= m_uiTimeEnd)
{
//两段时间有交集
oMeetTime.m_uiTimeStart = min(m_uiTimeStart,oMeetTime.m_uiTimeStart);
oMeetTime.m_uiTimeEnd = max(m_uiTimeEnd,oMeetTime.m_uiTimeEnd);
m_bEnable = false;
return !m_bEnable;
}
else if (m_uiTimeStart >= oMeetTime.m_uiTimeStart && oMeetTime.m_uiTimeEnd >= m_uiTimeStart)
{
//两段时间有交集
oMeetTime.m_uiTimeStart = min(m_uiTimeStart,oMeetTime.m_uiTimeStart);
oMeetTime.m_uiTimeEnd = max(m_uiTimeEnd,oMeetTime.m_uiTimeEnd);
m_bEnable = false;
return !m_bEnable;
}
}
else
{
return false;
}
}
public:
unsigned int m_uiTimeStart;
unsigned int m_uiTimeEnd;
bool m_bEnable;
protected:
private:
};
class CMeetTimeMan
{
public:
bool AddMeetTime(const CMeetTime& oMeetTime)
{
if (!oMeetTime.m_bEnable)
{
return false;
}
CMeetTime oTemp = oMeetTime;
for (size_t sCurSize = 0;sCurSize < m_vecMeetTime.size(); sCurSize++)
{
m_vecMeetTime[sCurSize].MergeMeetTime(oTemp);
}
m_vecMeetTime.push_back(oTemp);
}
string OutputAllMeetTime()
{
string strOut;
map<unsigned int,CMeetTime> mapMeetOut;
for (size_t sCurSize = 0;sCurSize < m_vecMeetTime.size();sCurSize++)
{
CMeetTime oTemp = m_vecMeetTime[sCurSize];
if (oTemp.m_bEnable)
{
mapMeetOut[oTemp.m_uiTimeStart] = oTemp;
}
}
if (!mapMeetOut.empty())
{
strOut = "[";
for (map<unsigned int,CMeetTime>::iterator iterForLoop = mapMeetOut.begin();iterForLoop != mapMeetOut.end();iterForLoop++)
{
char buff[10];
memset(buff,0x00,10);
sprintf(buff,"[%d,%d],",iterForLoop->second.m_uiTimeStart,iterForLoop->second.m_uiTimeEnd);
strOut += buff;
}
*(strOut.end() - 1) = ']';
}
return strOut;
}
public:
vector<CMeetTime> m_vecMeetTime;
protected:
private:
};
int main()
{
CMeetTimeMan oTimeMan;
oTimeMan.AddMeetTime(CMeetTime (10,13));
oTimeMan.AddMeetTime(CMeetTime (7,11));
oTimeMan.AddMeetTime(CMeetTime (8,9));
oTimeMan.AddMeetTime(CMeetTime (2,3));
oTimeMan.AddMeetTime(CMeetTime (4,6));
oTimeMan.AddMeetTime(CMeetTime (3,5));
oTimeMan.AddMeetTime(CMeetTime (15,19));
//…………
string strOut = oTimeMan.OutputAllMeetTime();
cout << strOut << endl;
return 0;
}