Time Limit : 2000/1000ms (Java/Other) Memory Limit : 131072/65536K (Java/Other)
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.
#include <iostream> #include <algorithm> #include <string> #include <cstring> #include <queue> using namespace std; struct node { int s, e; }a[1000005]; bool cmp(node a, node b)//贪心 { if (a.s == b.s)//开始时间短的在前 return a.e<b.e; else return a.s<b.s; } int main() { int n, t; int i; cin >> n >> t; for (i = 1; i <= n; i++) { cin >> a[i].s >> a[i].e; } a[n + 1].s = 999999999;//最后一个开始时间设为无穷大 sort(a + 1, a + 1 + n, cmp); int mm = 0; int ans = 0; bool f = 0; int ss =0; for (i = 1; i <= n; i++) { if (a[i].s <=ss+1 )//是ss+1 { if (a[i].e > mm) { mm = a[i].e; f = 1; } if (a[i + 1].s > ss+1 && f == 1) { ss = mm; ans++; f = 0; } } } if (ss>=t) cout << ans << endl; else cout << "-1" << endl; return 0; }