`
JAVA那点事
  • 浏览: 17308 次
  • 性别: Icon_minigender_1
  • 来自: 宁波
社区版块
存档分类

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);
		}
	}
}
 

 

分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics