列表

详情


NC24867. [USACO 2009 Dec S]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

原站题解

上次编辑到这里,代码来自缓存 点击恢复默认模板

pypy3(pypy3.6.1) 解法, 执行用时: 300ms, 内存消耗: 28120K, 提交时间: 2020-05-16 00:44:36

import io, os
#input = io.BytesIO(os.read(0,os.fstat(0).st_size)).readline
R = lambda : map(int, input().split())
n = int(input())
a = [tuple(R()) for _ in range(n)]
a.sort(key=lambda x:x[1])
l, r = a[0]
ans = 1
for i in a[1:] :
    if r <= i[0] :
        ans += 1
        l, r = i
print(ans)

C++ 解法, 执行用时: 39ms, 内存消耗: 808K, 提交时间: 2021-10-09 21:34:19

#include<bits/stdc++.h>
using namespace std;
int N, a, p;
pair<int, int>s[50009]; 
int main()
{
	cin >> N;
	for(int i = 0; i < N; i++)
		cin >> s[i].second >> s[i].first;
	sort(s, s+N);
	for(int i = 0; i < N; i++)
		if(s[i].second >= p)
			a ++, p = s[i].first;
	cout << a;
}

Python3(3.5.2) 解法, 执行用时: 187ms, 内存消耗: 14140K, 提交时间: 2020-07-24 10:45:03

n=int(input())
a=[[int(i) for i in input().split()]for j in range(n)]
a.sort(key=lambda x:x[1])
sum=0
end=-1
for i in range(n):
    if a[i][0]>=end:
        sum+=1
        end=a[i][1]
print(sum)

上一题