洛谷 P2970 [USACO09DEC]Selfish Grazing S

48 篇文章 0 订阅
2 篇文章 0 订阅

题目描述

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 S_i and ends at location E_i (1 <= S_i < E_i; S_i < E_i <= 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 S_i >= E_j or E_i <= S_j. 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.

约翰有N(1≤N≤50000)头牛,约翰的草地可以认为是一条直线.每只牛只喜欢在某个特定的范围内吃草.第i头牛喜欢在区间(Si,Ei)吃草,1≤Si<Ei≤1,000,000,00.

奶牛们都很自私,他们不喜欢和其他奶牛共享自己喜欢吃草的领域,因此约翰要保证任意

两头牛都不会共享他们喜欢吃草昀领域.如果奶牛i和奶牛J想要同时吃草,那么要满足:Si>=Ej或者Ei≤Sj.约翰想知道在同一时刻,最多可以有多少头奶牛同时吃草?

输入格式

* Line 1: A single integer: N

* Lines 2..N+1: Line i+1 contains the two space-separated integers: S_i and E_i

输出格式

* 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 

输出 #1

3 

 

看到这道题

很容易想到的排序方式就是,左端点排序,跨度值排序

可是这道题

恰恰相反

是右端点排序

因为他要看n个区间内,哪些是不重合的

所以需要把右端点排序,然后才能和上一个区间比较

其他的就没什么难点了

AC代码:

# include <iostream>
# include <cstdio>
# include <algorithm>
using namespace std;
# define int long long
int n,r=1,cnt;//r右边界 
struct node{
	int s;
	int e;
}a[50005];
bool cmp(node x,node y){
	return x.e<y.e;
}
signed main(){
	scanf("%lld",&n);
	for (int i=1;i<=n;i++){
		scanf("%lld%lld",&a[i].s,&a[i].e);
	}
	sort(a+1,a+1+n,cmp);
	for (int i=1;i<=n;i++){
		if (r<=a[i].s){
			cnt++;
			r=a[i].e;
		}
	}
	printf("%lld",cnt);
	return 0;
}

 

  • 3
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值