1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77
|
#include <algorithm>
#include <ciso646>
#include <iostream>
#include <iterator>
#include <sstream>
#include <string>
#include <vector>
#include <utility>
using namespace std;
struct interval_t: public pair <int, int>
{
// This ctor isn't actually used in this example...
interval_t( int first, int second ): pair <int, int> ( first, second ) { }
// Ctor from string of form "3..72" == [3,72]
interval_t( const string& s )
{
istringstream ss( s );
ss >> first;
while (ss.peek() == '.') ss.get();
ss >> second;
}
// Endeavor to modify self as intersection of self and r. Returns true on success.
bool try_intersect( const interval_t& r )
{
bool result = !(r.second < first) and !(r.first > second);
if (result)
{
first = max( first, r.first );
second = min( second, r.second );
}
return result;
}
};
// Print the interval for the user in "[3,72]" format
ostream& operator << ( ostream& outs, const interval_t& r )
{
return outs << "[" << r.first << "," << r.second << "]";
}
// Call as: "a.exe 5..8 3..4 13..20 7..10"
int main( int argc, char** argv )
{
vector <interval_t> intervals( argv + 1, argv + argc );
vector <interval_t> results;
size_t max_count = 0;
// While there are intervals,
// take the last and try to merge the remaining intervals,
// removing those for which it was successful
// If we merged at least as many as any previous attempt,
// store the final (merged) interval in the results.
// The results only contain final intervals obtained by
// merging the maximum number of input intervals.
while (intervals.size())
{
size_t count = 1;
interval_t r = intervals.back();
intervals.pop_back();
for (auto s = intervals.rbegin(); s != intervals.rend(); ++s)
if (r.try_intersect( *s ))
{
intervals.erase( s.base() );
count++;
}
if (count < max_count) continue;
if (count > max_count) results.clear();
max_count = count;
results.push_back( r );
}
cout << "Maximum of " << max_count << " people during the following intervals:\n";
copy( results.begin(), results.end(), ostream_iterator <interval_t> ( cout, "\n" ) );
}
|