题目描述
某餐馆有n张桌子,每张桌子有一个参数:a 可容纳的最大人数; 有m批客人,每批客人有两个参数:b人数,c预计消费金额。 在不允许拼桌的情况下,请实现一个算法选择其中一部分客人,使得总预计消费金额最大
输入描述:
输入包括m+2行。 第一行两个整数n(1 <= n <= 50000),m(1 <= m <= 50000) 第二行为n个参数a,即每个桌子可容纳的最大人数,以空格分隔,范围均在32位int范围内。 接下来m行,每行两个参数b,c。分别表示第i批客人的人数和预计消费金额,以空格分隔,范围均在32位int范围内。
输出描述:
输出一个整数,表示最大的总预计消费金额
示例1
输入
复制
3 5 2 4 2 1 3 3 5 3 7 5 9 1 10
输出
复制
20
解题思路:我们要获得的是最大的利润,那么就需要在有限的桌子的个数去把那些消费额高的批次的客人入座,同时在匹配的过程中,需要考虑到其占用的位置的个数应该尽量的和桌子可以容纳的位数相等,所以需要对桌子建立一个标志位;
对消费额进行降序排序,重写comparator实现,对桌子可以坐的人数升序排序;
注意:
1、在每次遍历为了减少查询时间,因已经完成排序,可以采用二分法;
2、对人数>桌子最大人数的进行忽略,continue即可;
3、对输入的数据进行存储,采用数组;
4、对comparator的重写,注意格式;
具体代码如下:
import java.util.*;
public class Main{
public static void main(String[] args){
Scanner sc = new Scanner(System.in);
while(sc.hasNext()){
int n = sc.nextInt(); // n table
int m = sc.nextInt(); // m customers
int[] table = new int[n];
for(int i=0;i<n;i++)
table[i]=sc.nextInt(); // volume of a table
int[][] cus = new int[m][2];
for(int j=0;j<m;j++){
cus[j][0]=sc.nextInt(); // number of customers
cus[j][1]=sc.nextInt(); // money
}
Arrays.sort(table);
Arrays.sort(cus, new Comparator<int[]>(){
public int compare(int[] a, int[] b){
return b[1]-a[1];
}
});//这里实现了按照消费的多少进行排序,降序排序
long res = 0L;
int index = 0;
boolean[] tableb = new boolean[n];
//按照来的人进行入座
for(int i=0;i<m;i++){
if(cus[i][0]>table[n-1])
continue;
//最多的人大于最多的桌子,继续
index = bs(table,cus[i][0]);
while(index<n && tableb[index]==true)
index++;//如果前面的桌子都坐满了,就index++
if(index<n){
res += cus[i][1];
tableb[index]=true;
}
}
System.out.println(res);
}
sc.close();
}
//这里采用二分法来获得该数所在的位置,找到数组中该元素的位置,返回的一定是low,而不是high
private static int bs(int[] num, int tar){
int low=0;
int high=num.length-1;
int mid=0;
while(low<=high){
mid=(high+low)/2;
if(num[mid]>=tar)
high=mid-1;
else
low=mid+1;
}
return low;
}
}