C++ 计算最小点积c++;

C++ 计算最小点积c++;,c++,algorithm,dot-product,C++,Algorithm,Dot Product,我试图计算两个数组/向量的最小点积。详情如下: 问题:给定两个序列a1,a2,和b1,b2,求第二序列的置换π,使a1,a2,…,的点积,和bπ1,bπ2,bπn是最小值 我的逻辑工作正常,但当我尝试输入如下内容时,由于整数溢出而失败。我将使用什么数据类型来适应我的条件1≤ N≤ 10^3; −10^5 ≤ 哎,比≤ 10^5适用于所有1≤ 我≤ n 一, 99999 99999 上述场景的输出应该是99998000001,但我得到的是1409865409 #include <algori

我试图计算两个数组/向量的最小点积。详情如下:

问题:给定两个序列a1,a2,和b1,b2,求第二序列的置换π,使a1,a2,…,的点积,和bπ1,bπ2,bπn是最小值

我的逻辑工作正常,但当我尝试输入如下内容时,由于整数溢出而失败。我将使用什么数据类型来适应我的条件1≤ N≤ 10^3; −10^5 ≤ 哎,比≤ 10^5适用于所有1≤ 我≤ n

一,

99999

99999

上述场景的输出应该是99998000001,但我得到的是1409865409

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

using std::vector;

int64_t min_dot_product(int n, vector<int> a, vector<int> b) {
    int64_t result = 0;
    if (n != 0)
    {
        std::sort(a.begin(), a.end());
        std::sort(b.begin(), b.end());
        std::reverse(a.begin(), a.end());

        /*for (long long int i = 0; i < n; i++) {
            result += a[i] * b[n - 1 - i];
        }*/

        result = std::inner_product(a.begin(), a.end(), b.begin(), 0);
    }
    return result;
}

int main() {
    int n;
    std::cin >> n;
    vector<int> a(n), b(n);
    for (int i = 0; i < n; i++) {
        std::cin >> a[i];
    }
    for (int i = 0; i < n; i++) {
        std::cin >> b[i];
    }
    std::cout << min_dot_product(n, a, b) << std::endl;
}
#包括
#包括
#包括
#包括
使用std::vector;
int64\t最小点积(intn,向量a,向量b){
int64_t结果=0;
如果(n!=0)
{
排序(a.begin(),a.end());
排序(b.begin(),b.end());
std::reverse(a.begin(),a.end());
/*for(长整型i=0;i>n;
向量a(n),b(n);
对于(int i=0;i>a[i];
}
对于(int i=0;i>b[i];
}

std::不能进行以下更改:

  • 向量
    替换为
    向量
    ,以64位整数存储数字

  • 使用
    result=std::内部产品(a.begin(),a.end(),b.begin(),0LL);

    0LL
    建议结果为
    int64\u t


  • 问题是,您将其存储在
    int32\t
    中,因此乘法溢出。

    您不应该更改a的顺序,只有b。而且,
    std::next\u permutation
    可能会引起您的兴趣。不,即使我也更改a的顺序,它也会起作用,我已经测试了相同的结果。事实上,您是对的。a顺序的任何更改都是错误的如果a不变,则与结果b中的变化相同。我试图了解我提出的问题是否有任何错误?因为有人投票反对。欢迎任何输入。@StoryTeller,
    int32\u t
    在我们的案例中不起作用。因为在
    std::internal\u product
    的库实现中,它会将值乘以ut将其转换为结果的数据类型。因此,
    int32\u t
    将相乘,结果溢出。您在这一点上大错特错。内积的返回类型与传递给它的初始值相同。对运算符的要求是,可以将它们的返回值转换为返回类型。长话短说,uNL除非从
    int32_t
    int64_t
    的隐式转换失败,否则您不必不必要地扩展向量。@StoryTeller,我屈服了,打开了标准草案。通过使用初始值
    init
    初始化累加器
    acc
    ,然后使用
    acc=acc+修改累加器来计算其结果(*i1)*(*i2)
    @chris,这就是我记得的。它也验证了Rishit的观点。我错误地认为它不会溢出。我希望整数提升可以拯救我们,但唉。@StoryTeller,有趣的是,如果我们的数据类型小于
    int
    ,比如
    short
    (假设它们在该实现上的大小不同)。在这种情况下,
    short
    s将在相乘之前提升为
    int
    s,这仅仅是因为语言使用整数运算符的方式。