2 2 8 6 1 1 4 5 2 10 6 4 5 6 5
1 2
区间覆盖问题分成三种情况(“---”表示区间)
第一种情况
a -----------
b --------------
c -----------
此时没有能覆盖b和c之间的区域
第二种情况
a -----------
b ------------
c -------------
此时需要选择a,b,c三个区间
第三种
a -----------
b -------------
c ---------------
此时选择a,c两个区间就能覆盖住,不需要选择3个区间
#include <iostream> #include <vector> #include <algorithm> #include <cmath> using namespace std; struct Segment{ double first,second; Segment(double first_ = 0, double second_ = 0):first(first_),second(second_){} bool operator < (const Segment& a) const{ if(first!=a.first) return first < a.first; else return second > a.second; } }; int main(){ int N; cin >>N; for(int icase = 0 ; icase < N; icase ++ ){ int n; double w,h; cin >> n >>w >> h; vector<Segment> segments; for(int i = 0 ; i < n; ++ i){ double x,r; cin >> x >>r; if(2*r >= h){ segments.push_back(Segment(x - sqrt(4*r*r-h*h)/2,x + sqrt(4*r*r-h*h)/2)); } } sort(segments.begin(),segments.end()); int cnt = 1; double left = segments[0].first, right = segments[0].second, prevRight = 0; for(int i = 1 ; i < segments.size(); ++ i){ if(segments[i].first > right ){ // 第一种情况 cnt = 0; break; }else if(segments[i].first >= prevRight){ //第二种情况 cnt++; prevRight = right; right = segments[i].second; }else if(segments[i].first < prevRight && segments[i].second > right){ //第三种情况 right = segments[i].second; } if(right >= w) break; } if(left<= 0 && right >= w) cout<<cnt<<endl; else cout<<0<<endl; } }
原文:http://www.cnblogs.com/xiongqiangcs/p/3670428.html