【问题标题】:For which cases does this algorithm fail? [closed]该算法在哪些情况下会失败? [关闭]
【发布时间】:2012-08-12 09:32:52
【问题描述】:

它做什么 - 索引“i”处的元素是除“i”处的输入元素之外的所有输入元素的乘积。

例如,如果 arr = { 1, 2, 3, 4 },那么

输出 = { 2*3*4, 1*3*4, 1*2*4, 1*2*3 }.

#include<cstdio>
#include<iostream>
using namespace std;
int main(){
    int n;
    long long int arr[1000]={0},prod=1;
    cin>>n;
    for(int i=0;i<n;i++){
        cin>>arr[i];
        prod*=arr[i];
    }
    if(prod!=0)
        for(int i=0;i<n;i++){
            cout<<(prod/arr[i])<<endl;
        }
    else
        for(int i=0;i<n;i++){
            cout<<"0"<<endl;
        }
    return 0;
}

【问题讨论】:

  • 你知道它失败了还是你要求人们进行代码审查?
  • 它失败了。我无法弄清楚是哪种情况
  • 你怎么知道它失败了?
  • 在线法官上运行它

标签: c++ algorithm testing


【解决方案1】:

失败的最简单情况是2 0 1。正确的结果是1 0,你的结果是0 0

更一般地说,如果输入集中恰好有一个零和至少一个非零,则它会失败。

【讨论】:

  • 这种情况下的输出是1 0 吗? {0*1,2*1,2*0} 应该是输出吧?
  • 第一个数字是计数(参见cin&gt;&gt;n)。数据集为0 1,大小为2
【解决方案2】:

如前所述,问题是当输入之一为零时,您尝试除以零。为了正确计算乘积,需要一种只执行乘法而不执行除法的算法,例如以下算法。

#include <stdio.h>
#include <stddef.h>

// Input: an array of 2^(exp) doubles
// Output: an array of 2^(exp) doubles, where each one is the
//         product of all the numbers at different indices in
//         the input
// Return value: the product of all inputs
double products (unsigned int exp, const double *in, double *out)
{
    if (exp == 0) {
        out[0] = 1;
        return in[0];
    }

    size_t half_n = (size_t)1 << (exp - 1);

    double prod_left = products(exp - 1, in, out);
    double prod_right = products(exp - 1, in + half_n, out + half_n);

    for (size_t i = 0; i < half_n; i++) {
        out[i] *= prod_right;
        out[half_n + i] *= prod_left;
    }

    return prod_left * prod_right;
}

int main ()
{
    double in[8] = {1, 2, 3, 4, 5, 6, 7, 8};
    double out[8];
    products(3, in, out);

    for (size_t i = 0; i < 8; i++) {
        printf("%f ", out[i]);
    }
    printf("\n");

    return 0;
}

这需要 O(n*log(n)) 时间并且没有额外的空间,除了递归使用的 O(log(n)) 空间。虽然它很好且易于理解,但它并不是最优的;见this question

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-11-08
    • 1970-01-01
    • 1970-01-01
    • 2015-04-28
    • 2023-04-01
    • 2014-07-29
    • 1970-01-01
    相关资源
    最近更新 更多