(algorithm) to determine whether two intervals overlap

Source: Internet
Author: User

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

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.