算法题(五十五):滴滴2017笔试题——餐馆

题目描述

某餐馆有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

分析

思路来源于牛客网

思路:优先选消费额度大的客人安排就餐

对客人按照消费额度排序(大->小)

对桌子按照容量排序(大->小)

选取当前消费额度最大客人:

1.如果没有桌子可用,结束;

2.如果人数过多无法安排,跳过;

3.如果可安排,则找到最合适的桌位,可就餐的桌位中容量最小的;

  3.1向这批客人收费;

  3.2将桌子从可用资源中删除;

直到没有桌子可用或所有客人全部安排

代码

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();
            int m = sc.nextInt();
            int[] disk = new int[n]; //桌子数组
            for (int i = 0; i < n; i ++) {
                disk[i] = sc.nextInt();
            }
            Arrays.sort(disk); // 桌子容纳量从小到大排序
            PriorityQueue<Customer> queue = new PriorityQueue<>(); // 将客人按消费额降序加入优先级队列
            for (int i = 0; i < m; i ++) {
                int b = sc.nextInt();
                int c = sc.nextInt();
                if(b <= disk[n - 1]) queue.add(new Customer(b, c)); // 如果人数小于桌子最大容纳量,加入队列
            }
            boolean[] visited = new boolean[n]; // 记录桌子是否被占用
            long sum = 0; // 记录总盈利
            int count = 0; // 记录已使用的桌子数
            while ( ! queue.isEmpty()) {
                Customer customer = queue.poll();
                for (int i = 0; i < n; i ++) { // 为客人分配桌子
                    if(customer.peopleCount <= disk[i] && ! visited[i]) {
                        sum += customer.moneyCount;
                        visited[i] = true;
                        count ++;
                        break;
                    }
                }
                if(count == n) break;
            }
            System.out.println(sum);
        }
    }
 
    static class Customer implements Comparable<Customer> {
        private int peopleCount;
        private int moneyCount;
 
        public Customer(int peopleCount, int moneyCount) {
            this.peopleCount = peopleCount;
            this.moneyCount = moneyCount;
        }
 
        @Override
        public int compareTo(Customer o) {
            if(o.moneyCount > this.moneyCount) return 1;
            else if(o.moneyCount < this.moneyCount) return - 1;
            return 0;
        }
    }
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值