bzoj 3410 [Usaco2009 Dec] Selfish Grazing The Selfish Herbivore

http://www.elijahqi.win/archives/3223
Description

约翰有N(1≤N≤50000)头牛,约翰的草地可以认为是一条直线.每只牛只喜欢在某个特定的范围内吃草.第i头牛喜欢在区间(Si,Ei)吃草,1≤Si<Ei≤1,000,000,00.
奶牛们都很自私,他们不喜欢和其他奶牛共享自己喜欢吃草的领域,因此约翰要保证任意

No two cows will share the area they like to graze. If cow i and cow J want to graze at the same time, they must satisfy: Si>=Ej or Ei≤Sj. John wants to know how many cows can be grazing at the same time?
Input

第1行:一个整数N.
第2到N+1行:第i+l行有两个整数Si,Ei.

Output

一个整数,最多可以有多少头牛同时吃草.

Sample Input

5
2 4
1 12
4 5
7 10
7 8
Sample Output

3
HINT

The 1st, 3rd, and 4th cows can graze at the same time, and the 1st, 3rd, and 5th can also.

Source

Silver

Very good elijahqi will not be greedy elijahqi is very good

Approach: Sort by the right endpoint if it can meet the requirements, then ++ans will ensure that the space left behind is the largest when the most line segments are used in the front.

#include<cstdio>
#include<cctype>
#include<algorithm>
using namespace std;
inline char gc(){
    static char now[1<<16],*S,*T;
    if(T==S){T=(S=now)+fread(now,1,1<<16,stdin);if (T==S) return EOF;}
    return *S++;
}
inline int read(){
    int x=0,f=1;char ch=gc();
    while(!isdigit(ch)) {if (ch=='-') f=-1;ch=gc();}
    while(isdigit(ch)) x=x*10+ch-'0',ch=gc();
    return x*f;
}
const int N=5e4+10;int n;
struct node{int l,r;}line[N];
inline bool cmp(const node &a,const node &b){
    return a.r<b.r;
}
int main(){
    freopen("bzoj3410.in","r",stdin);
    n=read();
    for (int i=1;i<=n;++i) line[i].l=read(),line[i].r=read();
    sort(line+1,line+n+1,cmp);int lst=0,ans=0;
    for (int i=1;i<=n;++i){
        if(line[i].l>=lst) ++ans,lst=line[i].r;
    }printf("%d\n",ans);
    return 0;
}

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=324909618&siteId=291194637