POJ 2376 Cleaning Shifts

原題:http://poj.org/problem?id=2376

 

 

題目:問有N頭牛,每頭牛的工作時間不同,要工作T小時,最少需要幾頭牛工作。即是:輸入 n 個區間和 t,接着輸入 n 個區間[st, ed], 要求找出最少的區間數覆蓋區間目標區間[1, t];

 

思路:先按開始時間從小到大、結束時間從大到小排序,然後再貪心。

 

代碼:(AC)

import java.util.Arrays;
import java.util.Comparator;
import java.util.Scanner;

public class Main {

	/**
	 * poj2376
	 * @param args
	 */
	static class Cows{
		int st;
		int ed;
	}
	static Cows[] cows = new Cows[25001];
	static int nNum ;
	static int tLength ;
	static int min_cow()
	{
		int count=1,j = 0;
		int cur=cows[0].st,cur_len=cows[0].ed,i=0;
		if(cur>1) return 0;
		if(cur_len>=tLength) return 1;
		while(i<nNum&&cur_len<tLength)
		{
			int max=0;
			int tag=0;
			while(i<nNum&&cows[i].st<=cur_len+1){
				if(cows[i].ed>max){ max=cows[i].ed;j=i;
				if(max>cur_len) tag=1;
				}
				i++;
			}
			i--;
			if(tag==0) return 0;
			cur_len=cows[j].ed;count++;
			if(i==nNum-1&&cur_len<tLength) return 0;
		}
		return count;
	}
	public static void main(String[] args) {
		Scanner in = new Scanner(System.in);
		while(in.hasNext())
		{
			nNum = in.nextInt();
			tLength = in.nextInt();
 			for(int i=0;i<nNum;i++)
			{
				cows[i] = new Cows();
				cows[i].st = in.nextInt();
				cows[i].ed = in.nextInt();
			}
			Arrays.sort(cows,0,nNum,new Comparator<Object>() {
				public int compare(Object o1, Object o2) {
					Cows a = (Cows)o1;
					Cows b = (Cows)o2;
					if(a.st<b.st)
						return -1;
					else if(a.st>b.st)
						return 1;
					else
					{
						if(a.ed<b.ed)
							return 1;
						else if(a.ed<b.ed)
							return -1;
						else 
							return 0;
					}
				};
			});
			int ans = min_cow();
			if(ans!=0&&ans<=nNum)
				System.out.println(ans);
			else
				System.out.println(-1);
		}
	}
}
 

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章