Дан двумерный массив. Найти:
а) минимальную сумму элементов строки;
б) максимальную сумму элементов столбца.
Обе задачи решить двумя способами:
1) с использованием дополнительного одномерного массива;
2) без использования дополнительного одномерного массива.
Answers & Comments
\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\
#include <iostream>
using namespace std;
int minSumRow1(int ** const a, const int N, const int M) {
int sum = 0;
int *buff = new int[N];
for (size_t i = 0; i < N; ++i) {
buff[i] = 0;
for (size_t j = 0; j < M; ++j)
buff[i] += a[i][j];
}
sum = buff[0];
for (size_t i = 1; i < N; ++i)
if (sum > buff[i])
sum = buff[i];
return sum;
}
int minSumRow2(int ** const a, const int N, const int M) {
int sum, buff;
bool flag = true;
for (size_t i = 0; i < N; ++i) {
buff = 0;
for (size_t j = 0; j < M; ++j)
buff += a[i][j];
if (flag || buff < sum) {
flag = false; sum = buff;
}
}
return sum;
}
int maxSumCol1(int ** const a, const int N, const int M) {
int sum = 0;
int *buff = new int[M];
for (size_t j = 0; j < M; ++j) {
buff[j] = 0;
for (size_t i = 0; i < N; ++i)
buff[j] += a[i][j];
}
sum = buff[0];
for (size_t j = 1; j < M; ++j)
if (sum < buff[j]) sum = buff[j];
return sum;
}
int maxSumCol2(int ** const a, const int N, const int M) {
int sum, buff;
bool flag = true;
for (size_t j = 0; j < M; ++j) {
buff = 0;
for (size_t i = 0; i < N; ++i)
buff += a[i][j];
if (flag || buff > sum) {
flag = false;
sum = buff;
}
}
return sum;
}
int main() {
setlocale(LC_ALL, "Russian");
const size_t N = 5, M = 6;
int **a = new int*[N];
cout << "Массив" << endl;
for (size_t i = 0; i < N; ++i){
a[i] = new int[M];
for (size_t j = 0; j < M; ++j){
a[i][j] = 1 + rand() % 9;
cout << a[i][j] << " ";
}
cout << endl;
}
cout << endl;
cout << minSumRow1(a, N, M) << endl;
cout << minSumRow2(a, N, M) << endl;
cout << maxSumCol1(a, N, M) << endl;
cout << maxSumCol2(a, N, M) << endl;
system("pause");
return 0;
}
\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\
Кодяра выше