Online JudgeProblem SetAuthorsOnline ContestsUser
Web Board
Home Page
F.A.Qs
Statistical Charts
Problems
Submit Problem
Online Status
Prob.ID:
Register
Update your info
Authors ranklist
Current Contest
Past Contests
Scheduled Contests
Award Contest
User ID:
Password:
  Register

贴Java代码。堆(优先队列) O(n*log n) ,带注释

Posted by haqishen at 2015-01-06 21:55:46 on Problem 2010 and last updated at 2015-01-13 20:31:28
//以分数高低排序
//然后以有可能成为中间值的cow的分数为中间值,分别求左右两边的最小的总cost并记录
//最后扫描这些有记录的cow,输出最佳答案。
//值得一提的是这道题还可以用二分查找来做,但计算量不变。
//主要步骤就是分别对成绩和钱排序,然后二分搜索成绩,按钱来进行检验。

import java.io.*;
import java.util.*;
public class Main {

	public static void main(String[] args) throws IOException {
		BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
		
//		该优先队列按aid从大到小降序
		Comparator<cow> cmpa = new Comparator<cow>(){
			public int compare(cow a, cow b){
				return b.f - a.f;
			}
		};		
		PriorityQueue<cow> pqJ = new PriorityQueue<cow>(1,cmpa);
		
//		输入数据
		String[] NCF = br.readLine().split("\\s");
		int N = new Integer(NCF[0]), C = new Integer(NCF[1]), F = new Integer(NCF[2]);
		cow cows[] = new cow[C];		
		for(int i = 0; i < C; i ++){
			cows[i] = new cow();
			String[] sf = br.readLine().split("\\s");
			cows[i].sc = new Integer(sf[0]);
			cows[i].f  = new Integer(sf[1]);
		}
//		按分数从大到小降序
		Arrays.sort(cows);
		
		int n = N/2;
		int costL = 0;
//		先让前N/2个cow进优先队列并计算aid的总和costL,
		for(int i = 0; i < n; i++){
			costL += cows[i].f;
			pqJ.add(cows[i]);
		}
//		然后依次对第N/2 到 (C-N/2)的cow进行处理,
//		将costL记录在当前cow中,
//		然后对比当前cow的aid和堆顶aid的大小,
//		如果当前cow较小,则删除堆顶cow,压入当前cow
//		更新costL,重复步骤1
		for(int i = n; i < C - n; i++){
			cows[i].costL = costL;
			int f = pqJ.peek().f;
			if(cows[i].f < f){
				costL += cows[i].f - f;
				pqJ.poll();
				pqJ.add(cows[i]);
			}
		}
//		用同样的方法计算costR
		pqJ.clear();
		int costR = 0;
		for(int i = C-1; i > C-1-n; i--){
			costR += cows[i].f;
			pqJ.add(cows[i]);
		}
		for(int i = C-1-n; i >= n; i--){
			cows[i].costR = costR;
			int f = pqJ.peek().f;
			if(cows[i].f < f){
				costR += cows[i].f - f;
				pqJ.poll();
				pqJ.add(cows[i]);
			}
		}
					
//		最后遍历第N/2 ~ (C-N/2)的cow计算其costL +  costR + aid的值
//		如果这个值 <=F 则是满足要求的,输出满足要求的最大值。
//		如果没有满足要求的,则输出-1
		int ans = -1;	
		for(int i = n; i < C - n; i++){
			int cost = cows[i].costL + cows[i].costR +cows[i].f;
			if(cost <= F)
				ans = Math.max(ans, cows[i].sc);			
		}
		
		System.out.println(ans);
	}
}

class cow implements Comparable<cow>{
	int sc, f,
		costL = -1, costR = -1;
//	按分数从大到小降序
	public int compareTo(cow o) {
		return o.sc - this.sc;
	}
}

Followed by:

Post your reply here:
User ID:
Password:
Title:

Content:

Home Page   Go Back  To top


All Rights Reserved 2003-2013 Ying Fuchen,Xu Pengcheng,Xie Di
Any problem, Please Contact Administrator