1.区间选点和最大不相交区间数量【妙啊】
#include <bits/stdc++.h>
using namespace std;
const int N=100010;
int n;
struct Range
{
int l,r;
bool operator<(const Range &W) const
{
return r<W.r;
}
}range[N];
int main()
{
scanf("%d",&n);
for(int i=0;i<n;i++) scanf("%d%d",&range[i].l,&range[i].r);
sort(range,range+n);
int res=0,ed=-2e9;
for(int i=0;i<n;i++)
if(range[i].l>ed)
{
res++;
ed=range[i].r;
}
printf("%d\n",res);
return 0;
}
2.区间分组
#include <bits/stdc++.h>
using namespace std;
const int N=100010;
int n;
struct Range
{
int l,r;
bool operator <(const Range &W) const
{
return l<W.l;
}
}range[N];
int main()
{
scanf("%d",&n);
for(int i=0;i<n;i++)
{
int l,r;
scanf("%d%d",&l,&r);
range[i]={l,r};
}
sort(range,range +n);
priority_queue<int, vector<int>,greater<int> >heap;
for(int i=0;i<n;i++)
{
auto r=range[i];
if(heap.empty()||heap.top()>=r.l) heap.push(r.r);
else
{
heap.pop();
heap.push(r.r);
}
}
printf("%d\n",heap.size());
return 0;
}
3.区间覆盖
#include <bits/stdc++.h>
using namespace std;
const int N=100010;
int n;
struct Range
{
int l,r;
bool operator<(const Range &W)const
{
return l<W.l;
}
}range[N];
int main()
{
int st,ed;
scanf("%d%d",&st,&ed);
scanf("%d",&n);
for(int i=0;i<n;i++)
{
int l,r;
scanf("%d%d",&l,&r);
range[i]={l,r};
}
sort(range,range+n);
int res=0;
bool success=false;
for(int i=0;i<n;i++)
{
int j=i,r=-2e9;
while(j<n&&range[j].l<=st)
{
r=max(r,range[j].r);
j++;
}
if(r<st)
{
success=false;
break;
}
res++;
if(r>=ed)
{
success=true;
break;
}
st=r;
i=j-1;
}
if(!success) res=-1;
printf("%d\n",res);
return 0;
}
4.112.雷达设备
#include <bits/stdc++.h>
using namespace std;
const int N=1010;
int n,d;
struct Segment
{
double l,r;
bool operator<(const Segment& t) const
{
return r<t.r;
}
}seg[N];
int main()
{
scanf("%d%d",&n,&d);
bool failed=false;
for(int i=0;i<n;i++)
{
int x,y;
scanf("%d%d",&x,&y);
if(y>d) failed=true;
else
{
double len=sqrt(d*d-y*y);
seg[i]={x-len,x+len};
}
}
if(failed) puts("-1");
else
{
sort(seg,seg+n);
int cnt=0;
double last=-1e20;
for(int i=0;i<n;i++)
if(last<seg[i].l)
{
cnt++;
last=seg[i].r;
}
printf("%d\n",cnt);
}
return 0;
}