我试图解决一个问题,我输入两个不同长度的向量并添加它们的标量积。它是https://code.google.com/codejam/contest/32016/dashboard#s=p0提出的最小标量乘积问题。显然,我没有希望地运行一个无限loop.Probably,因为permutation.But,我不明白为什么。
#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;
}发布于 2015-04-01 15:40:23
@NathanOliver的评论是正确的。我认为问题在于你的设计。对于您正在考虑的问题,有一个更容易的解决方案;最小标量向量就是一个向量的最大值乘以另一个向量的最小。考虑下面的守则:
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。
https://stackoverflow.com/questions/29394219
复制相似问题