贪心——切长条

39 篇文章 1 订阅

贪心——切长条

题目描述

给定如图所示的若干个长条。你可以在某一行的任意两个数之间作一条竖线,从而把这个长条切开,并可能切开其他长条。问至少要切几刀才能把每一根长条都切开。样例如图需要切两刀。
在这里插入图片描述
注意:输入文件每行的第一个数表示开始的位置,而第二个数表示长度。

输入描述:

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.

示例

输入

7
2 4
4 7
3 3
5 3
9 4
1 5
7 3

输出

2

分析

这题可以先按最小结束位置排序并将cnt和sum置0,然后从前往后遍历,如果某个长条开始的位置大于或等于cnt,那么就把这个长条的结束位置赋值给cnt,sum也要加一,最后输出sum值。

#include<cstdio>
#include<cstring>
#include<cstdlib>
#include<iostream>
#include<algorithm>
using namespace std;
int n;
struct node{
	int a,b;
}f[100001];
bool cmp(node x,node y)
{
	if(x.b==y.b){
		return x.a<y.a;
	}
	else{
		return x.b<y.b;
	}
}
int main()
{
	cin>>n;
	for(int i=0;i<n;i++){
		cin>>f[i].a>>f[i].b;
		f[i].b=f[i].a+f[i].b;
	}
	sort(f,f+n,cmp);
	int cnt=0;
	int sum=0;
	for(int i=0;i<n;i++){
		if(cnt<=f[i].a){
			cnt=f[i].b;
			sum++;
		}
	}
	cout<<sum<<endl;
	return 0;
}
  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值