c++ - Bank Kattis 问题的算法正确性

标签 c++ algorithm

This是我指的问题。快速总结:

输入:一个整数时间T;银行关闭的时间(以分钟为单位)和一组 ct 表示此人携带的现金数量(整数)和从现在开始的时间(以分钟为单位)如果没有送达,此人将离开。服务一个人需要一分钟,您必须最迟在 t 时间开始服务一个人。

输出:在关闭时间内可以收取的最大金额。

我的方法是:将所有人放在一张将金钱与时间对应起来的 map 上。我按钱对这张 map 进行排序。然后我做了一个类似队列的结构,我把钱最多的人放在尽可能远的地方。如果该位置已被占用,那么我将继续前进,直到找到一个位置。如果我不能,那么我就不会添加这个人。

下面是我的辅助函数,用于确定我是否可以插入一个人。

// returns index where we can insert, otherwise -1
int canInsert(bool* queue, int timeToInsert) {
    if (!queue[timeToInsert]) {
        return timeToInsert;
    } else {
        int index = timeToInsert-1;
        while (index >= 0) {
            if (!queue[index]) {
                return index;
            } else {
                index--;
            }
        }
        return -1;
    }
}

这里是主要的驱动函数:

// moneyToTime is a map that maps a person's money to the time value
int Bank(int T, map<int, int> moneyToTime) {
    int answer = 0;
    bool queue[47] = {0};
    for (map<int,int>::reverse_iterator i = moneyToTime.rbegin(); i != moneyToTime.rend(); i++) {
        if (T > 0) {
            // try to insert. If we can, then add to sum. Otherwise, don't.
            int potentialIndex = canInsert(queue, i->second);
            if (potentialIndex != -1) {
                queue[potentialIndex] = 1;
                answer += i->first;
                T--;
            }
        } else {
            break;
        }
    }
    return answer;
}

从逻辑上讲,这对我来说很有意义,而且它几乎通过了所有测试用例。有一对失败了;我看不出它们是什么。测试用例错误实际上表明错误的答案,而不是糟糕的运行时错误。有人可以帮我看看我的方法中的谬误吗?

最佳答案

您没有展示如何构建 moneyToTime但无论如何它看起来像map<int, int>是错误的类型。想象一下,你有很多人拥有相同数量的金钱和不同的时间。那么您将如何在您的 moneyToTime 中表示? ?

如果我的理论是正确的,像这样的例子应该会破坏你的解决方案:

3 3
2000 2
2000 1
500 2

显然最好的总和是 4000 = 2000 + 2000。我怀疑你只能得到 2500。

关于c++ - Bank Kattis 问题的算法正确性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54300139/

相关文章:

c++ - 检查应用程序是否安装在 MAC OS X 上?

c++ - 如何在 Windows 不分配盘符的情况下创建分区?

python - 如何找到 3 个大集合的交集的 100 个元素的列表?

c - 对超过 2 种类型的查询使用惰性传播

C++:结构会被正确复制吗?

c++ - 为什么我添加一个 "&",它输出不同?

html - POCO HTMLForm 如何读取名称为 invoice[items][1] 的输入表单元素

algorithm - 选择具有最小总体差异的数字对

java - 计算数组中不是每个元素的约数的元素数

algorithm - 生成升序序列 2^p*3^q