【问题标题】:I am trying to solve a question where i need array sum values but the code is not working I want to do something like this我正在尝试解决一个我需要数组总和值但代码不起作用的问题我想做这样的事情
【发布时间】:2018-10-04 10:45:29
【问题描述】:
Input:4
Input: 4 2 3 6
Output :29

解释:

  • 对数组进行排序,然后添加 2+3=5 现在我们有 5 4 6
  • 接下来我们添加 5+4=9 现在我们有 9 和 6
  • 接下来我们添加 9+6=15,最后我们返回 29 作为解,它是 5+9+15=29 的总和

我必须为此编写代码。

这是我的代码:

#include<bits/stdc++.h>
using namespace std;
int main()
{
    int num;
    cin >> num;
    vector<int> box;
    for (int i = 0; i < num; i++)
    {
        int temp;
        cin >> temp;
        box.push_back(temp);
    }
    sort(box.begin(), box.end());
    vector<int> res;
    int sum = box[0];
    if (box.size() == 1)
    {
        cout << sum;
    }
    else
    {
        for (int i = 1; i < box.size(); i++)
        {
            sum = sum + box[i];
            res[i] = sum;
        }
        res[0] = 0;
        int result = 0;
        for (int i = 0; i < res.size(); i++)
        {
            result += res[i];
        }
        cout << result;
    }
}

代码无法正常运行并且遇到错误,有人可以帮忙吗? 这个问题似乎很简单,但我无法提出有效的解决方案。

【问题讨论】:

  • vector&lt;int&gt; res(num); 当您调用[] 时,res 为空。
  • 与您的问题无关,但bits/stdc++.husing namespace std; 的双重组合是一个非常糟糕的主意。事实上,最好避免两者。
  • 请不要上传文字图片,而是在此处复制文字本身。链接可能会变坏,一些雇主会阻止图像,最重要的是:如果图像是代码,我们无法将代码复制到我们自己的 IDE。因此,请复制您的问题陈述的文本,而不是发布它的图片。另外,请详细说明“无法正常工作”。至少添加错误消息和行号,以便我们知道要查找的内容。
  • 这看起来像是来自某个算法问题网站的竞争问题/问题。如果是这种情况,您可以发布指向原始来源的链接吗?否则,您能否分享输入值的数量及其大小的限制?

标签: c++ algorithm


【解决方案1】:

鉴于已排序的vector&lt;int&gt; box,您要查找的值可以分配给foo,如下所示:

foo += box[0] + box[1];
foo += box[0] + box[1] + box[2];
foo += box[0] + box[1] + box[2] + box[3];

很明显,对于给定的从零开始的元素索引i,它将被添加到foosize(box) - i 次(除了将添加size(box) - 1 次的第一个元素。)所以你可以很简单地写出这样的逻辑:

auto foo = box.front() * (size(box) - 1);

for(auto i = 1; i < size(box); ++i) {
    foo += box[i] * (size(box) - i);
}

这显然期望box 中至少有2 个元素(如果box 为空,这甚至是未定义的。)所以显然这需要包含在if-check 中。无论如何,如果您信任 accumulatetake your mutable lambda correctly,您可以直接返回这个总和,如下所示:

accumulate(next(cbegin(box)), cend(box), box.front() * (size(box) - 1), [i = size(box)](const auto lhs, const auto rhs) mutable { return lhs + rhs * --i; })

Live Example

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-07-27
    • 2019-11-07
    • 2023-03-25
    • 1970-01-01
    • 2021-08-13
    • 1970-01-01
    相关资源
    最近更新 更多