soj 1792. Hengheng's Problem

本文介绍了一种通过排序和遍历来找出一天中最长空闲时间段的方法,特别适用于需要处理多个忙碌时间段的情况。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

题意:

亨亨的一天有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);
	}
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值