POJ2431Expedition 优先队列

这篇博客介绍了POJ2431 Expedition问题的解题思路,主要利用优先队列来优化加油策略。在经过每个加油站时,将可获得的汽油量Bi加入优先队列,当卡车燃料耗尽时,从队列中取出最大汽油量进行加油,以此确保能到达终点。
摘要由CSDN通过智能技术生成
原题链接
解题思路

在到达加油站 i 时,就获得了一次在之后的任何时候都可以加Bi 单位汽油的权利。每次从优先队列中取出最大的汽油。
· 在经过加油站 i 时,向优先队列中加入Bi
· 当燃料箱空时,如果优先队列也是空的,则无法到达终点。否则取出优先队列中最大的元素,给卡车加油

import java.util.Comparator;
import java.util.PriorityQueue;
import java.util.Queue;
import java.util.Scanner;

public class POJ2431{

	static int[] c = new int[10005];
	static int[] d = new int[10005];
	static int[] a = new int[10005];
	static int[] b = new int[10005];
	static int n,L,P;
	/*
	static Comparator<Integer> cmp = new Comparator<Integer>() {
	      public int compare(Integer e1, Integer e2) {
	        return e2 - e1;
	      }
	};*/
	    
	public static void main(String[] args) {
		// TODO Auto-generated method stub
		Scanner sc = new Scanner(System.in);
		
		n = sc.nextInt();
		for(int i = 0; i < n; i++) {
			c[i] = sc.nextInt();
			d[i] = sc.nextInt();
		}
		L = sc.nextInt();
		P = sc.nextInt();
		int t = n - 1;
		for(int i = 0; i < n; i++) {
			a[t] = L - c[i];
			b[t] = d[i];
			t--;
		}
		
		// 终点也是加油站
		a[n] = L;
		b[n] = 0;
		n++;

		int ans = 0;	//加油的次数
		int pos = 0;	//现在位置
		int rank = P;	//油量
		//Queue<Integer> que = new PriorityQueue<>(cmp);
		// 从大到小排序
		Queue<Integer> que=new PriorityQueue<Integer>(new Comparator<Integer>(){
			 public int compare(Integer e1, Integer e2) {
			        return e2 - e1;
			 }
		});
		for(int i = 0; i < n; i++) {
 			int d = a[i] - pos;
 			while(rank - d < 0) {
 				if(que.isEmpty()) {
 					System.out.println("-1");
 					return;
 				}
 				rank += que.poll();
 				ans++;
 				
 			}
 			rank -= d;
 			pos = a[i];
 			que.add(b[i]);
 		}
 		System.out.println(ans);
	}
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值