跳到正文

题解

题解 P2970 【[USACO09DEC]自私的放牧Selfish Grazing】

微香玉烛暗约 2 分钟
原文
文章信息与版本

文章信息

发布
2019年9月22日
收录
2026年10月6日
更新
2026年11月13日
篇幅
约 2 分钟
获赞
8
题目
P2970

版本

  1. v1当前

一道关于区间的简单贪心,但是有些迷惑性。很多人一看到题目就把数据按左端点排序,但是应当按右边端点,因为要求最多牛吃草时刻,所以看这头牛的结束时间,每次用开始时间比较,并更新ansans。(初值为11)

没听懂?
没关系,结合数据一起分析:

代码
2 4 
1 12 
4 5 
7 10 
7 8 

排序后就成了

代码
2 4 
4 5 
7 8
7 10 
1 12 

nownow初始值为44,ans=1ans=1,从第二个开始枚举。
① 4>=44>=4,所以now=5now=5,ans++ans++
② 7>=57>=5,所以now=8now=8,ans++ans++
③ 7<87<8,不变
④ 7<87<8,不变
⑤ 1<81<8,不变

ans=3ans=3

C++
# include <cstdio>
# include <iostream>
# include <algorithm>
using namespace std;
const int N=50005;
int n,ans=1,now;

struct node {
	int x,y;
	friend bool operator < (const node &p,const node &q) {
		return p.y<q.y;
	}
}a[N];

/*
另一种写法cmp
bool cmp (node x,node y) {
    return x.y<y.y;
}
*/

int main () {
	scanf ("%d",&n);
	for (int i=1;i<=n;i++)
		scanf ("%d%d",&a[i].x,&a[i].y);
	sort (a+1,a+1+n);
	now=a[1].y;
	for (int i=2;i<=n;i++) {
		if (a[i].x>=now) {
			ans++;
			now=a[i].y;
		}
	}//如上分析代码实现
	printf ("%d\n",ans);
	return 0;
}
//By苍空的蓝耀