C++程序:计算使和与积均不为零所需的步数
假设我们有一个包含n个元素的数组A。在一个操作中,我们可以将数组A中任何一个现有元素加1。如果数组中所有元素的和或积等于零,我们可以再进行一次此操作。我们需要计算使数组中所有元素的和与积都不为零所需的最小步数?
因此,如果输入类似于A = [-1, 0, 0, 1],则输出为2,因为积和和都为0。如果我们将1加到第二个和第三个元素,则数组将变为[−1,1,1,1],和将等于2,积将等于−1。
步骤
为了解决这个问题,我们将遵循以下步骤:
sum := 0 cnt := 0 n := size of A for initialize i := 0, when i < n, update (increase i by 1), do: x := A[i] sum := sum + x cnt := cnt + (if x is same as 0, then 1, otherwise 0) return (if sum + cnt is same as 0, then cnt + 1, otherwise cnt)
示例
让我们来看下面的实现以更好地理解:
#include <bits/stdc++.h> using namespace std; int solve(vector<int> A) { int sum = 0, cnt = 0; int n = A.size(); for (int i = 0; i < n; i++) { int x = A[i]; sum += x; cnt += x == 0 ? 1 : 0; } return sum + cnt == 0 ? cnt + 1 : cnt; } int main() { vector<int> A = { -1, 0, 0, 1 }; cout << solve(A) << endl; }
Explore our latest online courses and learn new skills at your own pace. Enroll and become a certified expert to boost your career.
输入
{ -1, 0, 0, 1 }
输出
2
广告