【贪心+排序】poj 2376 Cleaning Shifts

先按照开始时间升序排序,再按照结束时间升序排序,每次都挑选结束时间最晚的区间,直到把整个区间覆盖。边界情况比较多,而且还有一个很违背常识的地方,上一头牛t时刻结束,下一头牛可以从t+1时刻开始,而不是t时刻。。。

#include <iostream>
#include <algorithm>
#include <utility>
#include <stdio.h>

using namespace std;
int main(){
	int n, t;
	pair<int, int> inter[25005];
	scanf("%d%d", &n, &t);
	for(int i=0; i<n; i++)
		scanf("%d%d", &inter[i].first, &inter[i].second);
	sort(inter, inter+n);
	int res = 0;
	bool solution = true;
	if(inter[0].first != 1){
		solution = false;	
	}
	int pre = 1;
	int cur = -1;	
	for(int i=0; i<=n; i++){		
		if(inter[i].first != 1 && inter[i-1].first == 1 && res==0){
			pre = inter[i-1].second;		
			cur = -1;
			res++;
			if(pre >= t)
				break;
			i--;			
			continue;
		}
		if(inter[i].first == 1)
			continue;
		if(inter[i].first<=pre+1 && i!=n){
			if(inter[i].second <= pre)
				continue;
			cur = max(cur, inter[i].second);
		}
		else{
			//cout<<"pre: "<<pre<<endl;
			if(i==n && cur<t){
				solution = false;
				break;
			}
			if(cur <= pre){				
				solution = false;
				break;
			}
			pre = cur;
			cur = -1;
			res++;
			//cout<<inter[i].first<<" "<<inter[i].second<<endl;  
			i--;
			if(pre >= t)
				break;			
		}
	}
		
	if(solution == false)
		cout<<-1<<endl;
	else
		cout<<res<<endl;
	//system("pause");
	return 0;
}


你可能感兴趣的:(【贪心+排序】poj 2376 Cleaning Shifts)