C++のマトリックスのすべての行に共通する個別の要素を検索します
コンセプト
与えられたmxm行列に関して、問題は、行列のすべての行に共通するすべての個別の要素を決定することです。したがって、要素は任意の順序で表示できます。
入力
mat[][] = { {13, 2, 15, 4, 17},
{15, 3, 2, 4, 36},
{15, 2, 15, 4, 12},
{15, 26, 4, 3, 2},
{2, 19, 4, 22, 15}
} 出力
2 4 15
メソッド
最初の方法:3つのネストされたループを実装します。最初の行の要素が後続のすべての行に存在するかどうかを確認します。ここで、時間計算量はO(m ^ 3)です。重複する要素を制御するには、追加のスペースが必要になる場合があります。
2番目の方法:行列のすべての行を昇順で個別に配置または並べ替えます。次に、3つのソートされた配列の共通要素を決定する問題の修正されたアプローチを実装します。同じものの実装に続いて与えられます。
例
// C++ implementation to find distinct elements
// common to all rows of a matrix
#include <bits/stdc++.h>
using namespace std;
const int MAX1 = 100;
// Shows function to individually sort
// each row in increasing order
void sortRows1(int mat1[][MAX1], int m){
for (int i=0; i<m; i++)
sort(mat1[i], mat1[i] + m);
}
// Shows function to find all the common elements
void findAndPrintCommonElements1(int mat1[][MAX1], int m){
//Used to sort rows individually
sortRows1(mat1, m);
// Shows current column index of each row is stored
// from where the element is being searched in
// that row
int curr_index1[m];
memset(curr_index1, 0, sizeof(curr_index1));
int f = 0;
for (; curr_index1[0]<m; curr_index1[0]++){
//Indicates value present at the current column index
// of 1st row
int value1 = mat1[0][curr_index1[0]];
bool present1 = true;
//Indicates 'value' is being searched in all the
// subsequent rows
for (int i=1; i<m; i++){
// Used to iterate through all the elements of
// the row from its current column index
// till an element greater than the 'value'
// is found or the end of the row is
// encountered
while (curr_index1[i] < m &&
mat1[i][curr_index1[i]] <= value1)
curr_index1[i]++;
// Now if the element was not present at the column
// before to the 'curr_index' of the row
if (mat1[i][curr_index1[i]-1] != value1)
present1 = false;
// Now if all elements of the row have
// been traversed
if (curr_index1[i] == m){
f = 1;
break;
}
}
// Now if the 'value' is common to all the rows
if (present1)
cout << value1 << " ";
// Now if any row have been completely traversed
// then no more common elements can be found
if (f == 1)
break;
}
}
// Driver program to test above
int main(){
int mat1[][MAX1] = { {13, 2, 15, 4, 17},{15, 3, 2, 4, 36},{15, 2, 15, 4, 12},
{15, 26, 4, 3, 2},{2, 19, 4, 22, 15}};
int m = 5;
findAndPrintCommonElements1(mat1, m);
return 0;
} 出力
2 4 15
-
C ++で配列のすべての個別のサブセット(またはサブシーケンス)の合計を検索します
整数のセットがあるとします。与えられたセットのサブセットから形成できる明確な合計を見つけて、昇順で印刷します。配列要素の合計は小さいです。配列要素が[1、2、3]のようなものだと考えてください。出力は0、1、2、3、4、5、6になります。個別のサブセットは{}、{1}、{2}、{3}、{1、2}、{2、3}、{1です。 、3}、{1、2、3}、合計値は0、1、2、3、3、5、4、6です。 これを解決するために、動的計画法のアプローチを使用します。指定された要素の合計が小さい場合、配列のサイズを含む行を含むDPテーブルを作成できます。列のサイズは、指定された配列内のすべての要素の合計になります
-
Pythonで行列のすべての行に共通する個別の要素を見つける
次数mxmの正方行列があるとします。与えられた行列のすべての行に共通するすべての異なる要素を見つける必要があります。 したがって、入力が次のような場合 13 2 15 4 17 15 3 2 4 36 15 2 15 4 12 15 26 4 3 2 2 19 4 22 15 この場合、出力は[2,4,15]になります。 これを解決するには、次の手順に従います- 関数sortRows()を定義します。これにはマトリックスが必要です n:=行数 0