poj 2376 Cleaning Shifts

题意:

约翰让一些奶牛做家务,每只奶牛都有固定工作的时间段。

现在安排最少的奶牛,使得每一个单位时间内至少有一只奶牛在工作,问是否可行。

思路:

经典的贪心,区间覆盖问题。

把起始时刻0作为当前时刻开始寻找,找到区间左端点小于等于当前时刻+1且区间右端点最大的一个区间,直到下一个区间的左端点大于当前时刻+1,然后判断是否找到满足条件的区间,若找到,那么答案加一并且把找到的区间的右端点作为当前时刻。

如果最后找打的当前时刻小于T,那么说明找不到满足条件的区间使得所有的时刻都被覆盖。

代码:

 1 #include <stdio.h>
 2 #include <vector>
 3 #include <iostream>
 4 #include <algorithm>
 5 using namespace std;
 6 
 7 struct node
 8 {
 9     int st,en;
10     node(){};
11     node(int a,int b)
12     {
13         st = a;
14         en = b;
15     }
16 };
17 
18 vector<node> g;
19 
20 const int inf = 0x3f3f3f3f;
21 
22 bool cmp(node aa,node bb)
23 {
24     return aa.st < bb.st;
25 }
26 
27 int main()
28 {
29     int n,t;
30     
31     while(scanf("%d%d",&n,&t) != EOF)
32     {
33         g.clear();
34         
35         for (int i = 0;i < n;i++)
36         {
37             int x,y;
38             scanf("%d%d",&x,&y);
39             g.push_back(node(x,y));
40         }
41         
42         g.push_back(node(inf,inf));
43         
44         sort(g.begin(),g.end(),cmp);
45         
46         int ans = 0;
47         int cur = 0;
48         int tmp = 0;
49         bool f = 0;
50         
51         for (int i = 0;i < n;i++)
52         {
53             if (g[i].st <= cur + 1)
54             {
55                 if (g[i].en > tmp)
56                 {
57                     tmp = g[i].en;
58                     f = 1;
59                 }
60                 
61                 if (g[i+1].st > cur + 1 && f)
62                 {
63                     f = 0;
64                     cur = tmp;
65                     ans++;
66                 }
67             }
68         }
69         
70         if (cur < t) cout << -1 << endl;
71         else cout << ans << endl;
72     }
73     
74     return 0;
75 }
原文地址:https://www.cnblogs.com/kickit/p/8808149.html