牛客1.13 Selfish Grazing(思维,区间)

5 篇文章 0 订阅

第13节 Selfish Grazing
Each of Farmer John’s N (1 <= N <= 50,000) cows likes to graze in a certain part of the pasture, which can be thought of as a large one-dimeensional number line. Cow i’s favorite grazing range starts at location Si and ends at location Ei (1 <= Si < Ei; Si < Ei <= 100,000,000).
Most folks know the cows are quite selfish; no cow wants to share any of its grazing area with another. Thus, two cows i and j can only graze at the same time if either Si >= Ej or Ei <= Sj. FJ would like to know the maximum number of cows that can graze at the same time for a given set of cows and their preferences.
Consider a set of 5 cows with ranges shown below:
… 1 2 3 4 5 6 7 8 9 10 11 12 13 …
… |----|----|----|----|----|----|----|----|----|----|----|----|----
Cow 1: <=:=> : : :
Cow 2: <:::=>:
Cow 3: : <
> : : :
Cow 4: : : <====:=> :
Cow 5: : : <
> : :

These ranges represent (2, 4), (1, 12), (4, 5), (7, 10), and (7, 8), respectively.
For a solution, the first, third, and fourth (or fifth) cows can all graze at the same time. If the second cow grazed, no other cows could graze. Also, the fourth and fifth cows cannot graze together, so it is impossible for four or more cows to graze.

输入描述:

  • Line 1: A single integer: N
  • Lines 2…N+1: Line i+1 contains the two space-separated integers: Si and Ei

输出描述:

  • Line 1: A single integer representing the maximum number of cows that can graze at once.
    示例1
    输入
    5
    2 4
    1 12
    4 5
    7 10
    7 8
    输出
    3

两头牛不能共享吃草区域,要满足:Si>=Ej或者Ei≤Sj。问同一时间最多几只牛在吃草

思路:
按照右边界从小到大排序
如果有一个区间的左边界大于等于前一个选择区间的右边界,则两个区域没有冲突 ,两个牛可以同时吃草

#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.r<y.r;
}

int main()
{
	int n;
	cin>>n;
	for(int i=1;i<=n;i++)
	{
		cin>>p[i].l>>p[i].r;
	} 
	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;
		}
	}
	cout<<ans;
	return 0;

 } 
 /*
5 
2 4 
1 12 
4 5 
7 10 
7 8 
 
 */
 
 
 
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值