简体   繁体   English

零子序列问题 - 我的 C++ 解决方案有什么问题?

[英]Zero Subsequences problem - What's wrong with my C++ solution?

Problem Statement: Given an array arr of n integers, count the number of non-empty subsequences of the given array such that their product of maximum element and minimum element is zero.问题陈述:给定一个包含 n 个整数的数组 arr,计算给定数组的非空子序列的数量,使得它们的最大元素和最小元素的乘积为零。 Since this number can be huge, compute it modulo 10 ^ 9 + 7 A subsequence of an array is defined as the sequence obtained by deleting several elements from the array (possible none) without changing the order of the remaining elements.由于这个数字可能很大,因此以 10 ^ 9 + 7 为模计算一个数组的子序列定义为通过从数组中删除几个元素(可能没有)而不改变剩余元素的顺序而获得的序列。

Example Given n = 3, arr = [1, 0, – 2].示例 给定 n = 3,arr = [1, 0, – 2]。

There are 7 subsequences of arr that are- arr 有 7 个子序列是-

[1], minimum = 1, maximum =1, min * max = 1. [1],最小值 = 1,最大值 =1,最小值 * 最大值 = 1。

[1,0] minimum = 0, maximum=1, min * max=0 [1,0] 最小值 = 0,最大值 = 1,最小值 * 最大值 = 0

[ 1,0, – 2], minimum = – 2, maximum =1, min* max = -2. [ 1,0, – 2],最小值 = – 2,最大值 =1,最小值 * 最大值 = -2。

[0], minimum = 0, maximum =0, min * max=0 [0],最小值=0,最大值=0,最小值*最大值=0

[0,-2],minimum=-2,maximum=0, min* max=0, [0,-2],最小值=-2,最大值=0,最小值*最大值=0,

[1, -2] minimum=-2, maximum=1,min* max=-2 [1, -2] 最小值=-2,最大值=1,最小值* 最大值=-2

[- 2] minimum =-2 maximum = – 2, min* max = 4. [- 2] 最小值 =-2 最大值 = – 2,最小值 * 最大值 = 4。

There are 3 subsequences whose minimum * maximum = 0 that are有 3 个最小 * 最大 = 0 的子序列是

[1, 0], [0], [0, – 2]. [1, 0], [0], [0, – 2]。 Hence the answer is 3 .因此答案是3

I tried to come up with a solution, by counting the number of zeroes, positive numbers and negative numbers and then adding possible subsequences(2^n, per count) to an empty variable.我试图想出一个解决方案,通过计算零、正数和负数的数量,然后将可能的子序列(2^n,每个计数)添加到一个空变量。

My answer is way off though, it's 10 when the expected answer is 3. Can someone please point out my mistake?我的答案很遥远,预期答案是 3 时是10。有人可以指出我的错误吗?

#include<bits/stdc++.h>
using namespace std;
#define int long long

int zeroSubs(vector<int> arr){
    int x = 0, y = 0, z = 0, ans = 0;
    for(int i = 0; i < arr.size(); i++){
        if(arr[i] == 0) z++;
        else if(arr[i] < 0) x++;
        else y++;
    }
    ans += ((int)pow(2, z))*((int)pow(2, x));
    ans += ((int)pow(2, y))*((int)pow(2, z));
    ans += ((int)pow(2, z));

    return ans;
}

int32_t main()
{
//directly passed the sample test case as an array
    cout<<zeroSubs({1, 0, -2});
    return 0;
}
ans += ((1<<z)-1)*((1<<x)-1);
ans += ((1<<y)-1)*((1<<z)-1);
ans += ((1<<z)-1);

Made this slight change in the logic, thanks a lot to everyone for the valuable feedback.在逻辑上做了这个小改动,非常感谢大家的宝贵反馈。 It works now.现在可以了。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM