計算偵察單位形成方式的 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;
}輸入
{ 10, 20, 50, 60, 65 }, 10輸出
6
廣告
資料結構
網路
RDBMS
作業系統
Java
iOS
HTML
CSS
Android
Python
C 程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP