题意:
亨亨的一天有N段时间是繁忙的,(一天从00:00 ~ 23:59),求亨亨最长的一段空闲时间(如果有多段同等最长,输出较前的一段)。
输入的时间如08:00 18:00表示[08:00:00, 18:00:00]。
思路:
将繁忙时间按照开始时间排序。遍历即可。
注意:
开头的一段时间(从00:00开始)和末尾一段时间(到23:59)需要单独考虑
代码:
#include <cstdio>
#include <algorithm>
using namespace std;
struct Time
{
int h, m;
Time() {}
Time(int _h, int _m): h(_h), m(_m) {}
bool operator < (const Time &t) const
{
if (h != t.h) return h < t.h;
return m < t.m;
}
int Count(Time &t)
{
return (t.h - h) * 60 + t.m - m;
}
};
struct Period
{
Time s, e;
Period() {}
Period(Time _s, Time _e): s(_s), e(_e) {}
};
bool cmp(const Period &a, const Period &b)
{
return a.s < b.s;
}
Period busy[105];
int n, mPeriod, tPeriod, cnt;
Time st, ed, ast, aed;
int main()
{
while (~scanf("%d", &n), n)
{
for (int i = 0; i < n; ++ i)
{
scanf("%d:%d %d:%d", &st.h, &st.m, &ed.h, &ed.m);
busy[i] = Period(st, ed);
}
mPeriod = 0;
cnt = 0;
sort(busy, busy+n, cmp);
st = Time(0,0);
ed = busy[cnt].s;
while (cnt < n)
{
tPeriod = st.Count(ed);
if (tPeriod > mPeriod)
{
mPeriod = tPeriod;
ast = st;
aed = ed;
}
st = busy[cnt].e;
cnt ++;
while (cnt < n && busy[cnt].s < st)
{
if (st < busy[cnt].e)
st = busy[cnt].e;
cnt ++;
}
ed = busy[cnt].s;
}
ed = Time(23,59);
tPeriod = st.Count(ed);
if (tPeriod > mPeriod)
{
mPeriod = tPeriod;
ast = st;
aed = ed;
}
if (mPeriod == 0) printf("Poor Hengheng\n");
else printf("%02d:%02d %02d:%02d\n", ast.h, ast.m, aed.h, aed.m);
}
}