首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >由于next_permute而运行无限循环

由于next_permute而运行无限循环
EN

Stack Overflow用户
提问于 2015-04-01 14:59:55
回答 1查看 134关注 0票数 2

我试图解决一个问题,我输入两个不同长度的向量并添加它们的标量积。它是https://code.google.com/codejam/contest/32016/dashboard#s=p0提出的最小标量乘积问题。显然,我没有希望地运行一个无限loop.Probably,因为permutation.But,我不明白为什么。

代码语言:javascript
复制
#include "stdafx.h";
#include <algorithm>
#include <fstream>
using namespace std;

//output stuff
int cases[100];
int casesol[100];
int ncase;
void output()
{
    for (int i = 1; i <= ncase; i++)
    {
        printf("Case #%d: %d\n", i, casesol[i]);
    }
}

//output stuff end
int product;
int v1[100];
int v2[100];
int minimum;
int main()
{

    // read in number of cases
    freopen("file.in", "r", stdin);
    freopen("file.out", "w", stdout);
    scanf("%d", &ncase);

    // read in misc problem constants
    for (int i = 1; i <= ncase; ++i) {
        int vector_size;
        scanf("%d", &vector_size);

        // read in data

        //v1= new int [vector_size];
        //v2=new int [vector_size];

        for (int j = 0; j < vector_size; ++j){
            scanf("%d", &v1[j]);
        }
        for (int j = 0; j < vector_size; ++j){
            scanf("%d", &v2[j]);
        }

        // problem solving logic here
        do{
            for (int j = 0; j < vector_size; ++j){
                product += v1[j] * v2[j];
            }
            if (product<minimum)
                minimum = product;
        } while (next_permutation(v2 + 0, v2 + (vector_size - 1)));
        casesol[i] = minimum;
    }
    output();
    return 0;
}
EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2015-04-01 15:40:23

@NathanOliver的评论是正确的。我认为问题在于你的设计。对于您正在考虑的问题,有一个更容易的解决方案;最小标量向量就是一个向量的最大值乘以另一个向量的最小。考虑下面的守则:

代码语言:javascript
复制
const int size = 3;

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

std::sort(v1.begin(), v1.end());
std::sort(v2.begin(), v2.end());

int product = 0;
for (int i = 0; i < size; i++)
{
    product += v1[i] * v2[size-1-i];
}

这是您链接的页面中的第一个示例(硬编码而不是从文件中读取)。我得到的结果是正确的,-25

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/29394219

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档