c++ - LeetCode1011。二进制搜索,C++和Python的思想相同,但输出不同

标签 c++

有人可以看看我的CPP代码吗?
是因为这个问题:https://leetcode.com/problems/capacity-to-ship-packages-within-d-days/
尽管我的python代码有效,但我感到非常沮丧,因为我的cpp代码不能一如既往地工作。 :pensive:相同的想法,不同的结果。它让我疯狂。
正确的输出应该是15
我的Python代码返回正确的输出15,而我的CPP代码返回错误的输出10
我的python代码:

def cnt_days(weights, k):
        total, cnt = 0, 1
        for w in weights:
            if total + w > k:
                total = 0
                cnt += 1
            total += w
        print(total, cnt)
        return cnt

def shipWithinDays(weights, D):
    left = max(weights)
    right = max(weights) * len(weights) // D + 1

    while left < right:
        mid = left + (right - left) // 2
        if cnt_days(weights, mid) > D:
            left = mid + 1
        else:
            right = mid
    return left           


if __name__ == "__main__":
    print(shipWithinDays([1,2,3,4,5,6,7,8,9,10], 5))
我的cpp代码:
#include <iostream>
#include <vector>
#include <algorithm>

using namespace std;

int cnt_days(vector<int>& weights, int K)
{
    int total = 0, cnt = 1;
    for (int w: weights)
    {
        if (total + w > K) 
        {
            total = 0;
            cnt++;
        }
        else total += w;
    }
    cout << total <<" "<<  cnt << endl;
    return cnt;
}

int shipWithinDays(vector<int>& weights, int D)
{
    int maximum = *max_element(weights.begin(), weights.end());
    int left = maximum;
    int right = maximum * weights.size() / D + 1;
    while (left < right)
    {
        int mid = left + (right - left)/2;
        if (cnt_days(weights, mid) > D)
            left = mid + 1;
        else
            right = mid;
    }
    return left;    
}

int main()
{
    vector<int> weights = {1,2,3,4,5,6,7,8,9,10};
    int D = 5;
    cout << shipWithinDays(weights, D) << endl;
    return 0;
}

最佳答案

删除其他

else total += w;
应该
total += w;

关于c++ - LeetCode1011。二进制搜索,C++和Python的思想相同,但输出不同,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62621262/

相关文章:

c++ - 检查字符串中的唯一字符

c++ - C/C++ : efficient way to use a vector returned by a function

c++ - 如何找到事件的 QMainWindow 实例?

c# - 如何创建包含 const 内容的 C# 列表?

c++ - OpenMP:嵌套并行化有什么好处?

c++ - 多个线程写入 std::cout 或 std::cerr

仅在 Visual Studio 中出现 C++ `vector iterators incompatible` 错误

c++ - 图片转换: RGBA to RGB

c++ - 将 boost 变体的 vector 过滤成新的 vector ?

c++ - 使用 std::cin 忽略/跳过标记