Topic:
There are n interval segments on one-dimensional axes, and two interval segments with the longest overlap interval are obtained.
The data structure of the interval segment is defined as follows:
struct interval{ int start; int end;};
Ideas:
First, the n interval segments are sorted by the left endpoint of the interval, i.e. start.
Then traverse all the intervals from the trip, compare the right end of the two intervals before and after the end;
Assume that the front and back intervals are [x1,y1],[x2,y2], because they are sequential traversal, so x2>=x1, consider the situation:
If Y2>=y1,
The overlapping portions of the interval after [X2,y2] and [x1,y1] do not exceed this interval, because their x>x2, and the overlapping interval size is (y1-x+1) or 0, so the size of the overlap with the interval [x1,y1] is the largest of y1-x2+1 or 0. (when x2>y1, two intervals do not intersect, that is, 0)
If Y2<y1,
Then it can only be said that the interval [x2,y2] is contained in [X1,y1], so that the size of the interval [x1,y1] overlaps with at least y2-x2+1, and the size of the interval 2 is y2-x2+1, so it is possible not to consider the overlap of other intervals and intervals [x2,y2] size.
In both cases, we can delete an interval, calculate the first case, you can delete interval 1, calculate the second case, you can delete the interval 2.
The total time complexity is: sort O (nlogn) + traverse O (n)
Code:
#include <iostream> #include <vector> #include <algorithm>using namespace std;struct interval{int sta Rt int end;}; BOOL CMP (const Interval &a,const Interval &b) {return a.start<b.start;} int Longestoverlap (vector<interval> &inters, int n) {sort (Inters.begin (), Inters.end (), CMP); for (int i=0;i<n;i++) {cout<<inters[i].start<< "" <<inters[i].end<<endl; } int maxoverlap=0; Interval Pre; Interval cur; Pre=inters[0]; int Len; for (int i=1;i<n;i++) {cur=inters[i]; if (cur.end>=pre.end) {Len=max (pre.end-cur.start+1,0); Maxoverlap=max (Maxoverlap,len); Pre=cur; } else Maxoverlap=max (maxoverlap,cur.end-cur.start+1); } return maxoverlap;} int main () {int n; while (1) {cin>>n; Vector<interval> inters (n); for (int i=0;i<n;i++) {Cin>>inters[i].start>>interS[i].end; } cout<<longestoverlap (Inters,n) <<endl; } return 0;}
Maximum overlap of intervals (written questions)