Cleaning Shifts
Time Limit: 1000MS | Memory Limit: 65536K | |
Total Submissions: 17736 | Accepted: 4516 |
Description
Farmer John is assigning some of his N (1 <= N <= 25,000) cows to do some cleaning chores around the barn. He always wants to have one cow working on cleaning things up and has divided the day into T shifts (1 <= T <= 1,000,000), the first being shift 1 and the last being shift T.
Each cow is only available at some interval of times during the day for work on cleaning. Any cow that is selected for cleaning duty will work for the entirety of her interval.
Your job is to help Farmer John assign some cows to shifts so that (i) every shift has at least one cow assigned to it, and (ii) as few cows as possible are involved in cleaning. If it is not possible to assign a cow to each shift, print -1.
Each cow is only available at some interval of times during the day for work on cleaning. Any cow that is selected for cleaning duty will work for the entirety of her interval.
Your job is to help Farmer John assign some cows to shifts so that (i) every shift has at least one cow assigned to it, and (ii) as few cows as possible are involved in cleaning. If it is not possible to assign a cow to each shift, print -1.
Input
* Line 1: Two space-separated integers: N and T
* Lines 2..N+1: Each line contains the start and end times of the interval during which a cow can work. A cow starts work at the start time and finishes after the end time.
* Lines 2..N+1: Each line contains the start and end times of the interval during which a cow can work. A cow starts work at the start time and finishes after the end time.
Output
* Line 1: The minimum number of cows Farmer John needs to hire or -1 if it is not possible to assign a cow to each shift.
Sample Input
3 10 1 7 3 6 6 10
Sample Output
2
题意:有个区间,选择尽量少的区间,使得这些区间完全覆盖某线段。
算法:将所有区间按左端点坐标从小到大排序,顺序处理每个区间。每次选择覆盖点的区间中右端点坐标最大的一个,并将更新为该区间的右端点坐标,直到选择的区间已包含。注意(1,2 )和(3,4)可以覆盖(1,4)。
1 #include <iostream> 2 #include <cstring> 3 #include <algorithm> 4 using namespace std; 5 6 struct Node 7 { 8 int x,y; 9 }node[25005]; 10 11 bool cmp(Node a,Node b){ 12 if(a.x == b.x) return a.y < b.y; 13 return a.x < b.x; 14 } 15 int main() 16 { 17 ios_base::sync_with_stdio(0); 18 cin.tie(0); 19 20 int n,t; 21 while(cin>>n>>t){ 22 int right = 1; 23 for(int i = 1;i <= n;i ++){ 24 cin>>node[i].x>>node[i].y; 25 right = max(node[i].y,right); 26 } 27 28 sort(node+1,node+n+1,cmp); 29 node[n+1].x = 0x3f3f3f; 30 31 if(node[1].x > 1 || right < t){ 32 cout<<-1<<endl; 33 continue; 34 } 35 36 int s = 0,ans = 0; 37 int flag = 0,maxn = 1;; 38 for(int i = 1;i <= n;i ++){ 39 if(node[i].x <= s+1){ 40 if(node[i].y > s){ 41 maxn = max(maxn,node[i].y); 42 flag = 1; 43 } 44 if(node[i+1].x > s+1 && flag){ 45 ans++; 46 s = maxn; 47 flag = 0; 48 } 49 } 50 } 51 if(s < t) cout<<-1<<endl; 52 else 53 cout<<ans<<endl; 54 } 55 return 0; 56 }