#include<iostream>
#include<vector>
#include<algorithm>
using namespace std;
struct Interval //区间定义
{
int start,end;
Interval(int _start, int _end):start(_start),end(_end){}
};
bool cmp(const Interval &lhs, const Interval &rhs)
{
return lhs.start < rhs.start;
}
vector<Interval> Merge(vector<Interval> &intervals )
{
const int n=intervals.size();
if(n<2) return intervals;
sort(intervals.begin(),intervals.end(),cmp); //排序
vector<Interval> ret;
int left=intervals[0].start, right = intervals[0].end; //left, right表示当前区间的可能的最大范围
for(int i=1;i<n;i++) //合并
{
if(intervals[i].start<=right)
{
right=max(intervals[i].end,right);
}
else
{
ret.push_back(Interval(left,right));
left = intervals[i].start;
right = intervals[i].end;
}
}
ret.push_back(Interval(left,right));
return ret;
}
int Search(const vector<Interval> &ret, const int x)
{
const int n = ret.size();
if(n==0) return -1;
int left=0,right=n-1;
while(left<=right)
{
int mid=left+(right-left)/2;
if (ret[mid].end < x) left=mid+1;
else right=mid-1;
}
if(ret[left].start<= x) return left; //返回所在区间号
return -1;
}
bool Search(vector<Interval> &ret,Interval &target)
{
const int n = ret.size();
if(n == 0) return false;
//分别寻找当前区间的左端点和右端点
int idx1 = Search(ret,target.start);
int idx2 = Search(ret,target.end);
//如果是同一个区间,则返回true
if(idx1 != -1 && idx2 != -1 && idx1==idx2) return true;
return false;
}
int main()
{
vector<Interval> A;
A.push_back(Interval(1,3));
A.push_back(Interval(2,4));
A.push_back(Interval(7,8));
A.push_back(Interval(5,10));
A.push_back(Interval(11,12));
vector<Interval> ret=Merge(A);
for( vector<Interval>::iterator i=ret.begin();i<ret.end();i++)
cout << (*i).start << "\t" << (*i).end << endl;
Interval target(2,5);
cout << Search(ret,target) << endl;
system("pause");
}