Greedy: Corral book

There N cattle grazing stall. 
Each stall in the same period of time can only be provided to a cow grazing, it may require multiple corral. 
Given N per cow cattle grazing start time A and time B grazing end, each cow in the [A, B] of this period will have been grazing. 
When there is an intersection of two cows grazing intervals (inclusive), two head of cattle can not be arranged in the same corral grazing. 
Seeking the minimum number corresponding to each animal stall and stall the program needs.
Input format 
Line 1: Input an integer N. 

The first 2..n + 1'd: Line + i . 1 A row input start time of i-th grazing cattle grazing and end time B, separated by a space between the numbers. 

Output Format 
Line 1: Input an integer representing the minimum required number of stalls. 

The first 2..n +1: Line + i 1 i-line input corral cattle placed in numbered, starting with 1, as long as the program can be legitimate. 

Data range 
. 1 ≤N≤ 50000 ,
 . 1 ≤A, B ≦ 1000000

 

Sample input:

5
1 10
2 4
3 6
5 8
4 7

  

Sample output:

4
1
2
3
2
4

 

The main question is to examine knowledge point range packets

See related knowledge points: https://www.cnblogs.com/myhnb/p/11243677.html

AC Code

#include<bits/stdc++.h>
using namespace std;
typedef pair<int,int> pii;
const int N = 5*1e4+10;
priority_queue<pii,vector<pii>,greater<pii> > g;
pair<pair<int,int>,int> p[N];
int d[N];
int n,cnt;

int main()
{
    scanf("%d",&n);
    for(int i=1;i<=n;i++)
    {
        p[i].second=i;
        scanf("%d%d",&p[i].first.first,&p[i].first.second);
    }
    sort(p+1,p+n+1);
    cnt=1;
    g.push(make_pair(p[1].first.second,1));
    d[p[1].second]=1;
    for(int i=2;i<=n;i++)
    {
        if(p[i].first.first<=g.top().first)
        {
            g.push(make_pair(p[i].first.second,++cnt));
            d[p[i].second]=cnt;
        }
        else
        {
            int now=g.top().first,z=g.top().second;
            g.pop();
            now=max(now,p[i].first.second);
            g.push(make_pair(now,z));
            d[p[i].second]=z;
        }
    }
    printf("%d\n",g.size());
    for(int i=1;i<=n;i++)printf("%d\n",d[i]);
    return 0;
}

  

Guess you like

Origin www.cnblogs.com/myhnb/p/11243700.html