dを見つけて、C++でc[i] =d * a [i] +b[i]として作成された配列c[]のゼロの数を最大化します。
コンセプト
M個の整数の2つの与えられた配列に関して、配列Cを想定します。ここで、i番目の整数はd * a [i] + b [i]になります。ここで、dは任意の実数として示されます。私たちのタスクは、配列Cが最大数のゼロを持ち、ゼロの数も出力するようにdを表示または印刷することです。
入力
a[] = {15, 40, 45}
b[] = {4, 5, 6} 出力
Value of d is: -0.133333 The number of zeros in array C is: 1 If we choose d as -0.133333 then we get one zero in the array C which is the maximum possible.
メソッド
上記の問題を解決するために、以下の手順に従います-
- 方程式をd=-b [i] / a [i] と書き直します。
- ハッシュテーブルを実装して、任意の実数の最大出現回数をカウントし、dの値を取得します。
- これで、ゼロの数が最大のカウント+(両方が0であるペアa[i]とb[i]の数)になると結論付けます。
例
// C++ program to implement the above
// approach
#include <bits/stdc++.h>
using namespace std;
// Shows function to find the value of d
// and find the number of zeros in the array
void findDandZeros1(int a[], int b[], int m){
// Shows hash table
unordered_map<long double, int> mpp1;
int count1 = 0;
// Performs iteration for i-th element
for (int i = 0; i < m; i++) {
// Now if both are not 0
if (b[i] != 0 && a[i] != 0) {
long double val1 = (long double)(-1.0 * b[i]) /
(long double)(a[i]);
mpp1[val1] += 1;
}
// Now if both are 0
else if (b[i] == 0 && a[i] == 0)
count1 += 1;
}
// Used to find max occurring d
int maxi1 = 0;
for (auto it : mpp1) {
maxi1 = max(it.second, maxi1);
}
// Used to print the d which occurs max times
for (auto it : mpp1) {
if (it.second == maxi1) {
cout << "Value of d is: "
<< it.first << endl;
break;
}
}
// Used to print the number of zeros
cout << "The number of zeros in array C is: "
<< maxi1 + count1;
}
// Driver code
int main(){
int a[] = { 15, 40, 45 };
int b[] = { 4, 5, 6 };
int m = sizeof(a) / sizeof(a[0]);
findDandZeros1(a, b, m);
return 0;
} 出力
Value of d is: -0.133333 The number of zeros in array C is: 1
-
C++を使用して文字列の部分文字列の数を見つける
この記事では、特定の文字列に形成できるサブ文字列(空ではない)の数を見つけるためのアプローチについて学習します。 Input : string = “moon” Output : 10 Explanation: Substrings are ‘m’, ‘o’, ‘o’, ‘n’, ‘mo’, ‘oo’, ‘on’, ‘moo’, ‘oon’ and &
-
C++を使用して停止ステーションの数を見つける
ポイントXとYの間にn個の中間駅があります。2つの駅が隣接しないように、s駅に停車するように列車を配置できるさまざまな方法の数を数えます。そのため、この記事では、停車駅の数を見つけるためのあらゆる可能なアプローチについて説明します。問題を見ると、sの駅数で列車を止めることができる組み合わせを見つける必要があることがわかります。 問題を解決するためのアプローチ 中間駅が8つあり、3つの中間駅で電車を止める方法を見つける必要がある例を見てみましょう。 n = 8, s = 3 (n-s)、つまり電車が止まらない駅が5つ残っています 電車が止まらないA、B、C、D、Eの5つの駅があります