Topic:
Determine if two intervals overlap
Ideas:
Assuming that the interval is expressed as [start,end], there are two intervals, a, B.
There are two types of relationships in two intervals: overlapping and non-overlapping
There are 4 overlapping cases, two types of intersection, two inclusions (it's easy to think, don't signal here)
There are two cases of non-overlap: A in front of B, a behind B
Therefore, it is easy to get the method of judging interval overlap:
1, positive judgment, list four kinds of overlapping cases, to meet one, then overlap;
2, reverse judgment, list two kinds of non-overlapping cases, if one is satisfied, then overlap;
The second method is obviously simpler.
Optimize forward judgment:
Consider the positive judgment of the four cases, in fact, as long as the Max (A.start,b.start) <=min (a.end,b,end), you can judge a B overlap. (Because the drawing is more troublesome, here does not indicate, can try on the paper)
Code:
#include <iostream>using namespace std;typedef struct{ int start; int end;} Interval;bool isoverlap_1 (Interval interval1,interval interval2) { if (Interval1.end<interval2.start | | Interval1.start>interval2.end) return false; return true;} BOOL Isoverlap_2 (Interval interval1,interval interval2) { if (max (Interval1.start,interval2.start) <=min ( interval1.end,interval2.end)) return true; return false;} int main () { Interval interval1,interval2; while (1) { if (cin>>interval1.start && cin>>interval1.end && cin>> Interval2.start && cin>>interval2.end) { if (isoverlap_2 (interval1,interval2)) cout< < "overlap" <<endl; else cout<< "Non-overlap" <<endl; } } return 0;}
(algorithm) to determine whether two intervals overlap