[USACO06FEB] Stall Reservations S (Construction)

Title description:

John ’s N (l <N <50000) cows are so difficult to wait for, they even have their own unique milking period. Of course, for a cow, her daily milking period is fixed, for the time period A to B includes time period A and time period B. Obviously, John must develop a control system to decide which cowshed each cow should be arranged to milk, because cows obviously do not want to be seen by other cows during milking.

John wants you to help him calculate: if you want to meet the requirements of the cows, and every cow must be milked every day, at least how many barns are needed • In which barn each cow should be milked. If there are multiple answers, you only need any one.

answer:

Many people on the Internet use greed, and I give an alternative approach here.

Obviously the bullpen has an upper limit, which is n.

Let us first assume that there are n bullpens. Put the start and end times of the cows in an array and mark them differently, sort them by time (the start time with the same time must be before the end time).

First of all, the n bullpens are free at first.

The number of free bullpens decreases by one at a start time, and the number of free bullpens increases by one at an end time.

We find the minimum value of the free cowshed after each operation. Obviously these cowsheds have never been used and are not needed. The remaining cowsheds are used.

We know that the structure of the smallest number of bullpens is very simple.

We first put all the free bullpens into a queue, and each time we want to use it, we will go to the queue, and every time we use it, we will put it back into the queue.

#include <iostream>
#include <cstdio>
#include <algorithm>
#include <queue>
using namespace std;
const int N = 50010;
int n;
int a[N], b[N];
struct node{
    int t, f, id;
}p[N << 1];
int top;
int lim, mi, num;
int ans[N];
queue<int> q;
bool cmp(node x, node y) {
    if (x.t == y.t) return x.f > y.f;
    return x.t < y.t;
}
int main() {
    scanf("%d", &n);
    for (int i = 1; i <= n; i++) {
        scanf("%d%d", &a[i], &b[i]);
        p[++top] = node{a[i], 1, i};
        p[++top] = node{b[i], 0, i};
    }
    sort(p + 1, p + 1 + top, cmp);
    mi = lim = n;
    for (int i = 1; i <= top; i++) {
        if (p[i].f == 1) {
            lim--;
        } else {
            lim++;
        }
        mi = min(mi, lim);
    }
    num = lim - mi;
    printf("%d\n", num);
    for (int i = 1; i <= num; i++) q.push(i);
    for (int i = 1; i <= top; i++) {
        if (p[i].f == 1) {
            ans[p[i].id] = q.front();
            q.pop();
        } else {
            q.push(ans[p[i].id]);
        }
    }
    for (int i = 1; i <= n; i++) {
        printf("%d", ans[i]);
        putchar('\n');
    }
    return 0;
}

 

Guess you like

Origin www.cnblogs.com/zcr-blog/p/12718381.html