牛吃草
每头农场主约翰的N(1<=N<=50,000)牛喜欢在牧场的某一部分放牧,这可以被认为是一条大的一维数列。牛I最喜欢的放牧范围从Si位置开始,结束在EI位置(1<=Si<EI;Si<Ei<=100,000,000)。
大多数人都知道母牛是很自私的,没有一头牛愿意和另一只母牛分享它的牧场。因此,当Si>=EJ或EI<=Sj时,母牛I和j只能同时放牧。FJ想知道某一组牛可以同时放牧的奶牛的最大数量以及它们的偏好。
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.
这是一种(简单)贪心算法,按end(E)排序从小到大(关键点),在比较S与前一个的E比较,如果小于E,则这俩个没有交集,故可以sum++;否则就不算;
#include <iostream> #include <bits/stdc++.h> using namespace std; #define N 50005 struct node1{ int S; int E; }; typedef struct node1 node; node a[N]; bool cmp(node a,node b) { return a.E < b.E; } int main() { int n,i; scanf("%d",&n); for(i=0;i<n;i++) { scanf("%d%d",&a[i].S,&a[i].E); } sort(a,a+n,cmp); int x = -1,sum =0; for(i=0;i<n;i++) { if(a[i].S>=x){ sum++;x = a[i].E; } } printf("%d",sum); }