计算侦察单位形成方式的 C++ 代码
假设我们有一个包含 n 个元素的数组 A 和另一个数字 d。根据梦境预备军的条例,一个侦察单位应严格包含两名士兵。由于这两名士兵的差别不太大,因此她们的身高最多相差 d 厘米。有 n 名士兵的身高存储在数组 A 中。有些士兵的身高相同。我们需要找出用这 n 名士兵组成侦察单位有多少种方法。
因此,如果输入像 A = [10, 20, 50, 60, 65];d = 10,则输出将为 6,因为 (10, 20),(20, 10),(50, 60),(60, 50),(60, 65),(65, 60) 是可能的单位。
步骤
要解决此问题,我们将遵循以下步骤 -
ans := 0 for initialize i := 1, when i < size of A, update (increase i by 1), do: for initialize j := 0, when j < i, update (increase j by 1), do: if |A[i] - A[j]| <= d, then: (increase ans by 1) return ans * 2
示例
让我们看看以下实施来获得更好的理解 -
#include <bits/stdc++.h> using namespace std; int solve(vector<int> A, int d){ int ans = 0; for (int i = 1; i < A.size(); i++) for (int j = 0; j < i; j++) if (abs(A[i] - A[j]) <= d) ans++; return ans * 2; } int main(){ vector<int> A = { 10, 20, 50, 60, 65 }; int d = 10; cout << solve(A, d) << endl; }
Explore our latest online courses and learn new skills at your own pace. Enroll and become a certified expert to boost your career.
输入
{ 10, 20, 50, 60, 65 }, 10
输出
6
广告