第14节 切长条
给定如图所示的若干个长条。你可以在某一行的任意两个数之间作一条竖线,从而把这个长条切开,并可能切开其他长条。问至少要切几刀才能把每一根长条都切开。样例如图需要切两刀。
注意:输入文件每行的第一个数表示开始的位置,而第二个数表示长度。
输入描述:
Line 1: A single integer, N(2 <= N <= 32000)
Lines 2…N+1: Each line contains two space-separated positive integers that describe a leash. The first is the location of the leash’s stake; the second is the length of the leash.(1 <= length <= 1e7)
输出描述:
Line 1: A single integer that is the minimum number of cuts so that each leash is cut at least once.
示例1
输入
7
2 4
4 7
3 3
5 3
9 4
1 5
7 3
输出
2
长条在不同的区间,问切几刀能把长条全部切到
思路:
将片段按左端点从小到大排序,依次遍历,当某个片段的左端点比之前的最小右端点还要大时(大于等于)就说明必须要再切一刀。
#include <bits/stdc++.h>
using namespace std;
const int N=50005;
const int maxn=1e8+5;
struct st{
int l;
int r;
}p[N];
bool cmp(st x,st y)//按照左边界从小到大排序
{
return x.l<y.l;
}
int main()
{
int n;
cin>>n;
for(int i=1;i<=n;i++)
{
int a,b;
cin>>a>>b;
p[i].l=a;
p[i].r=a+b;
}
sort(p+1,p+n+1,cmp);
int ans=1;
int tmp=p[1].r;
for(int i=2;i<=n;i++)
{
if(p[i].l>=tmp)//如果当前片段左边界比之前片段中最小的右边界还要大,就要再切一刀
{
ans++;
tmp=p[i].r;
}
else tmp=min(tmp,p[i].r);//如果不比之前大,就继续更新最小右端点
}
cout<<ans;
return 0;
}
/*
7
2 4
4 7
3 3
5 3
9 4
1 5
7 3
*/