[贪心] POJ2376 Cleaning Shifts (区间覆盖问题)

题目

描述
FJ分配 N (1 <= N <= 25,000) 只中的一些奶牛在牛棚附近做些清洁。 他总是要让至少一只牛做清洁。他把一天分成T段(1 <= T <= 1,000,000), 第一段是1,最后一段是T

每只奶牛只在一些时间段有空。奶牛如果选择某一段时间,则必须完成整段时间的工作

你的任务是帮助FJ安排一些奶牛,使每段时间至少有一只奶牛被安排来做这件事。并且奶牛数应尽可能小。如果不可能办到,输出-1  输入
* 第一行:N和T

* 第二行至N+1行: 每一行包括奶牛能工作的开始和结束时间。闭区间。  输出
*输出完成清洁所需最少的奶牛数,如果不可能办到,输出-1  样例输入

3 10
1 7
3 6
6 10

样例输出

2

提示
这道题输入数据很多,请用scanf而不是cin

输入说明

这里有3只奶牛和10个时间段cow #1 能在时间段1..7工作, cow #2 能在时间段3..6工作, cow #3 能在时间段6..10工作

输出说明:

选择 cows #1 和 #3即可,没有更优的方案了 .

思路

这里写图片描述

代码

// 由于此时POJ抽风,随意没测评,代码乱写,表达思路即可
#include "stdafx.h"
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <algorithm>
using namespace std;

const int maxn = 25000 + 3000;
struct node {
    int x, y;
    bool operator < (const struct node& rhs) const {
        return x < rhs.x;
    }
}A[maxn];
int n, t;

int main() {
    scanf("%d%d", &n, &t);
    for (int i = 0; i < n; i++)
        scanf("%d%d", &A[i].x, &A[i].y);
    sort(A, A + n);

    int x = 0, sp = 1, maxp = 0, ans = 0;
    bool flag = false, fail = false;
    while (x < n) {
        while (A[x].x <= sp) {
            if (flag) {
                if (A[x].y > A[maxp].y) maxp = x;
            }
            else {
                maxp = x;
                flag = true;
            }
            x++;
        }
        if (!flag) {
            fail = true;
            break;
        }
        sp = A[maxp].y + 1;
        ans++;
        flag = false;
        if (A[maxp].y >= t) break;
    }
    if (fail) printf("-1\n");
    else printf("%d\n", ans);

    system("PAUSE");
    return 0;
}

猜你喜欢

转载自blog.csdn.net/icecab/article/details/80561726