【问题标题】:Find the combination of two vector arrays which sums to maximum of all the other combinations in c++找到两个向量数组的组合,其总和为 C++ 中所有其他组合的最大值
【发布时间】:2017-10-08 21:22:37
【问题描述】:

要找到最大和对,其中一个元素取自一个向量数组,另一个元素取自第二个向量数组。我找到了这段代码here,但是当 v1 和 v2 的大小都变为 100000 作为输出时,这将失败数组大小超过限制并调用 abort。

#include <vector>
#include <algorithm>
#include <iostream>
#include <iterator>
typedef int T;
struct Fctor
{
    typedef std::vector<T>::iterator Iterator;
    Iterator it1, it2, begin, end;
    Fctor(Iterator begin1, Iterator end1, Iterator begin2)
    {
        begin = begin1;
        end = end1;
        it1 = begin1;
        it2 = begin2;
    }
    T operator()()
    {
        // T result = f(*it1, *it2);
        T result = (*it1) * (*it2);
        if(++it1 != end) return result;
        it1 = begin;
        ++it2;
        return result;
    }
};

int main()
{
    std::vector<T> v1; v1.push_back(1); v1.push_back(2);
    std::vector<T> v2; v2.push_back(3); v2.push_back(4); v2.push_back(5);
    std::vector<T> result(v1.size() * v2.size());
    Fctor fctor(v2.begin(), v2.end(), v1.begin());
    generate(result.begin(), result.end(), fctor);
    std::copy(result.begin(), result.end(),
        std::ostream_iterator<T>(std::cout, " "));
    std::cout << std::endl;
    // => 3 4 5 6 8 10
}

【问题讨论】:

  • 我有一些坏消息。看起来你的键盘坏了,TAB 键不能可靠地工作。由于缺乏逻辑缩进,显示的代码大多不可读。你应该更换你的键盘,并用清晰、符合逻辑的缩进重写你的代码,这样其他人就可以真正阅读它。
  • 答案不就是每个向量的最大元素吗?您不需要生成所有可能的对。
  • 有没有办法在小于 o(n^2) 的时间内检查两个向量的所有组合(任何内置函数左右。)
  • 有 NxM 组合,因此检查所有组合将是 NxM。为什么需要所有组合?最大和对可以在线性时间内找到(扫描每个向量的最大值)。

标签: c++ arrays vector


【解决方案1】:

最大和对只是每个向量中最大值的和。您不需要生成所有组合或临时向量。这是一个使用标准库算法的非常简单的 O(n) 实现。

#include <algorithm>
#include <iostream>
#include <vector>

int main()
{
    std::vector<int> v1{ 1,2 };
    std::vector<int> v2{ 3,4,5 };

    int max1 = *std::max_element(v1.begin(), v1.end());
    int max2 = *std::max_element(v2.begin(), v2.end());

    std::cout << "max sum = " << (max1 + max2) << '\n';
}

// max sum = 7

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2019-10-18
    • 1970-01-01
    • 1970-01-01
    • 2020-02-02
    • 2015-03-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多