Quite simple question. I add two sentinels to avoid boundary checks. However, the input format is tricky to handle. At first, I use scanf("%2d:%2d %2d:%2d%*[^/n]/n, ...) to read the input. After some WAs, I finally realize that there could be nothing left in a line after the time.
Code:
- /*************************************************************************
- * Copyright (C) 2008 by liukaipeng *
- * liukaipeng at gmail dot com *
- *************************************************************************/
- /* @JUDGE_ID 00000 10191 C++ "Longest Nap" */
- #include <algorithm>
- #include <cstdio>
- #include <deque>
- #include <fstream>
- #include <iomanip>
- #include <iostream>
- #include <list>
- #include <map>
- #include <queue>
- #include <set>
- #include <stack>
- #include <string>
- #include <vector>
- using namespace std;
- int const appcount = 102;
- int const linesize = 256;
- struct mytime
- {
- mytime(int h = 0, int m = 0) : hour(h), minute(m) {}
- int hour;
- int minute;
- };
- inline mytime operator-(mytime const& t1, mytime const& t2)
- {
- int m = (t1.hour - t2.hour) * 60 + t1.minute - t2.minute;
- return mytime(m / 60, m % 60);
- }
- inline bool operator>(mytime const& t1, mytime const& t2)
- {
- return t1.hour > t2.hour || t1.hour == t2.hour && t1.minute > t2.minute;
- }
- typedef pair<mytime, mytime> appointment;
- struct appcmp
- {
- bool operator()(appointment const& a1, appointment const& a2)
- {
- return a1.first.hour < a2.first.hour ||
- a1.first.hour == a2.first.hour && a1.first.minute < a2.first.minute;
- }
- };
- void find_nap(appointment *apps, int napps, mytime& start, mytime& last)
- {
- sort(apps + 1, apps + napps + 1, appcmp());
- last.hour = 0;
- last.minute = 0;
- for (int i = 0; i <= napps; ++i) {
- mytime t = apps[i+1].first - apps[i].second;
- if (t > last) {
- last = t;
- start = apps[i].second;
- }
- }
- }
- int main(int argc, char *argv[])
- {
- #ifndef ONLINE_JUDGE
- freopen((string(argv[0]) + ".in").c_str(), "r", stdin);
- freopen((string(argv[0]) + ".out").c_str(), "w", stdout);
- #endif
- int napps;
- for (int day = 1; cin >> napps; ++day) {
- appointment apps[appcount];
- for (int i = 1, c; i <= napps; ++i) {
- scanf("%2d:%2d %2d:%2d",
- &apps[i].first.hour, &apps[i].first.minute,
- &apps[i].second.hour, &apps[i].second.minute);
- cin.ignore(2048, '/n');
- }
- apps[0] = make_pair(mytime(9, 0), mytime(10, 0));
- apps[napps+1] = make_pair(mytime(18, 0), mytime(19, 0));
- mytime start, last;
- find_nap(apps, napps, start, last);
- printf("Day #%d: the longest nap starts at %02d:%02d and will last for ",
- day, start.hour, start.minute);
- if (last.hour > 0) printf("%d hours and ", last.hour);
- printf("%d minutes./n", last.minute);
- }
- return 0;
- }