[C++]CleaningShifts--POJ2376

[C++]Cleaning Shifts

Cleaning Shifts:
分配 N (1 <= N <= 25,000) 只中的一些奶牛在牛棚附近做些清潔。他總是要讓至少一隻牛做清潔。他把一天分成T段(1 <= T <= 1,000,000), 第一段是1,最後一段是T。每隻奶牛隻在一些時間段有空。奶牛如果選擇某一段時間,則必須完成整段時間的工作。你的任務是幫助FJ安排一些奶牛,使每段時間至少有一隻奶牛被安排來做這件事。並且奶牛數應儘可能小。如果不可能辦到,輸出-1

輸入格式:

  • 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.
    輸出格式:

  • 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.

輸入:
3 10
1 7
3 6
6 10
輸出:
2

解題思路:

需要使牛的工作時間將[1,T]鋪滿
將所有牛按開始時間從左到後排序
然後貪心選擇能接任工作(與正在工作的牛有交叉點),且結束時間最遠的牛

AC代碼

#include<iostream>
#include<algorithm>
using namespace std;

struct ST{
	int s;
	int e;
};

int n, t;
ST st[25001];

int cmp(ST a, ST b){
	return a.s<b.s;
}

int main(){
	

	scanf("%d%d", &n, &t);
	for(int i = 0; i<n; i++){
		scanf("%d%d", &st[i].s, &st[i].e);
	}
	sort(st, st+n, cmp);
	
	int end = 0;
	int pos = 0;
	int ans = 0;
	while(end < t){
		int start = end + 1;  //下頭牛的起始時間 
		
		for(int i = pos; i<n; i++){
			if(st[i].s <= start){  //如果與上頭已工作的牛有交叉部分  則尋找最遠結束時間 
				end = max(end, st[i].e);
			}
			else{
				pos = i;  // 所有能接任工作的牛都查過 
				break;
			}
		}
		
		if(start > end)  //沒有找到能接任工作的牛 
			break;
		ans++;
	}
	
	if(end < t)
		cout<<-1<<endl;
	else
		cout<<ans<<endl;
	return 0;
} 
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章