Консультация № 182246
18.02.2011, 12:35
54.94 руб.
0 18 3
Здравствуйте! У меня возникли сложности с таким вопросом:Помогите написать программу на языке С++. Под ОС Windows XP, среда Borland Builder C++ 6,2006. Программа должна быть написана с помощью структур и прокомментирована. Условие задачи:
Из входного потока вводится непрямоугольная матрица целых чисел [aij], i=1,....., m, j=1,....ni. Значения m и ni заранее не известны и вводятся из входного потока.
Сформировать новую матрицу, поменяв в исходной матрице местами первую строку со строкой, содержащей максимальное количество строго положительных значений, и последнюю строку со строкой, содержащей максимальное количество отрицательных значений.
Исходную и полученную матрицы вывести в поток.

Обсуждение

Неизвестный
18.02.2011, 14:13
общий
Адресаты:
Как-то так. Проверяйте на компилируемость, скидывайте ошибки, если будут
Код:
#include <iostream>
#include <vector>

using namespace std;

typedef vector <int> vi;

int main()
{
int m=0,n=0,//row count, column count
i=0,j=0,//counters
count_neg=0,count_pos=0,//value counters
num_neg=0,num_pos=0;//row positions
cin>>m;
cin>>n;
//source matrix
vector <vi> arr=vector <vi> (n,vi(m,0));
for(j=0;j<n;j++)
{
//local counts and a value buffer
int loc_count_neg=0,loc_count_pos=0,loc_val=0;
for(i=0;i<m;i++)
{
//input and count values
cin >> loc_val;
arr[j][i]=loc_val;
if(loc_val>0)++loc_count_pos;
if(loc_val<0)++loc_count_neg;
}
//check against previous and replace
if(loc_count_neg>count_neg)
{
count_neg=loc_count_neg;
num_neg=j;
}
if(loc_count_pos>count_pos)
{
count_pos=loc_count_pos;
num_pos=j;
}
}
cout<<"source:"<<endl;
for(j=0;j<n;j++)
for(j=0;j<n;j++)
{
for(i=0;i<m;i++)
cout<<arr[j][i]<<" ";
cout<<endl;
}
//resulting matrix
vector <vi> res=vector <vi>(n);
if((num_pos == n-1) && (num_neg == 0))
{
//Both are on oppsite ends. Just swap them.
res[0]=arr[num_pos];
res[n-1]=arr[num_neg];
}else if(num_pos==num_neg)
{
//Oops both are on the same line.
cout<<"Failed."<<endl<<
"Max negative row == max positive row"<<endl;
exit(1);
}else if(num_neg==0)
{
//max negative is on the first line
//Swap it first to avoid overwriting
res[n-1]=arr[num_neg];
res[num_neg]=arr[n-1];
res[0]=arr[num_pos];
res[num_pos]=arr[0];
}else{
//"generic" swap
res[0]=arr[num_pos];
res[num_pos]=arr[0];
res[n-1]=arr[num_neg];
res[num_neg]=arr[n-1];
}
for(j=1;j<n-1;j++)
{
if((j!=num_pos) && (j!=num_neg))
res[j]=arr[j];
}
cout<<"result:"<<endl;
for(j=0;j<n;j++)
{
for(i=0;i<m;i++)
cout<<res[j][i]<<" ";
cout<<endl;
}
return 0;

}


проверка:
Код:
$ for ((k=1;k<=4;k++)); do echo test$k ; cat test$k ; echo ""; ./t<test$k ; done
test1
6
5
1 -2 -3 -4 -5 -6
2 -4 6 -3 2 0
3 3 3 3 -4 0
4 2 -2 -6 4 0
5 2 3 4 5 9

source:
1 -2 -3 -4 -5 -6
2 -4 6 -3 2 0
3 3 3 3 -4 0
4 2 -2 -6 4 0
5 2 3 4 5 9
result:
5 2 3 4 5 9
2 -4 6 -3 2 0
3 3 3 3 -4 0
4 2 -2 -6 4 0
1 -2 -3 -4 -5 -6
test2
5
4
1 0 0 0 0
2 -4 6 -3 2
3 0 0 0 0
4 0 0 0 0

source:
1 0 0 0 0
2 -4 6 -3 2
3 0 0 0 0
4 0 0 0 0
Failed.
Max negative row == max positive row
test3
5
5
1 -2 -3 -4 -5
2 -4 6 -3 2
3 2 3 4 5
4 3 3 3 -4
5 2 -2 -6 4

source:
1 -2 -3 -4 -5
2 -4 6 -3 2
3 2 3 4 5
4 3 3 3 -4
5 2 -2 -6 4
result:
3 2 3 4 5
2 -4 6 -3 2
1 -2 -3 -4 -5
4 3 3 3 -4
1 -2 -3 -4 -5
test4
5
5
1 -4 6 -3 2
2 -2 -3 -4 -5
3 2 3 4 5
4 3 3 3 -4
5 2 -2 -6 4

source:
1 -4 6 -3 2
2 -2 -3 -4 -5
3 2 3 4 5
4 3 3 3 -4
5 2 -2 -6 4
result:
3 2 3 4 5
5 2 -2 -6 4
1 -4 6 -3 2
4 3 3 3 -4
2 -2 -3 -4 -5


давно
Мастер-Эксперт
325460
1469
18.02.2011, 14:43
общий
Вы бы лучше весь проект сразу :)
Об авторе:
to live is to die
Неизвестный
18.02.2011, 14:47
общий
Адресаты:
Цитата: CradleA
Вы бы лучше весь проект сразу :)

Не понял.
давно
Мастер-Эксперт
325460
1469
18.02.2011, 14:50
общий
не один файл, а весь проект, чтобы автор вопроса скачал и сразу запустил то что и у Вас.
Об авторе:
to live is to die
Неизвестный
18.02.2011, 14:58
общий
Адресаты:
Цитата: CradleA
не один файл, а весь проект, чтобы автор вопроса скачал и сразу запустил то что и у Вас.

Я не уверен в том, что он запустит.
Я не такого плохого мнения об авторе вопроса, чтобы предполагать, что он может запустить левый бинарник из интернета.
Вот собственно каталог с "проектом". Даже Makefile для такой мелочи не стал писать.
[offtop]Какого $@#$#$ лысого здесь нельзя прикреплять tar?[/offtop]
Прикрепленные файлы:
a2fdc40542d493d30cca456450c85a9d.7z
Неизвестный
18.02.2011, 15:20
общий
Из входного потока вводится непрямоугольная матрица целых чисел
давно
Посетитель
276566
297
18.02.2011, 15:54
общий
Здравствуйте! А вы можете разбить этот код на отдельные структуры так, чтобы главная функция main только делала вызов структур.
Неизвестный
18.02.2011, 16:06
общий
Адресаты:
Если речь идёт о непрямоугольной матрице, может быть, Вам нужно что-то типа этого? Тогда опять же понятно, к чему структуры упомянуты (структура данных != функция)
[code h=100]#include <conio.h>
#include <iostream>
using namespace std;

struct elem {
int cr;
int* row;
};

void printMatrix (elem* matr, int m)
{
for (int i=0; i<m; i++) {
cout << endl;
for (int j=0; j<matr[i].cr; j++)
cout << matr[i].row[j] << ' ';
}
}

int main(void)
{
int m,n,cr;
elem* matr = NULL;

cout << "Enter m: ";
cin >> m;
cout << "Enter n: ";
cin >> n;

matr = new elem [m];

for (int i=0; i<m; i++) {
cout << "Enter count for row " << i << ", <=" << n << ": ";
cin >> cr;
while (cr<=0 || cr>n) {
cout << "/nError! Reenter: ";
cin >> cr;
}
matr[i].cr = cr;
matr[i].row = new int [cr];
cout << "Enter elements:\n";
for (int j=0; j<cr; j++)
cin >> matr[i].row[j];
}

cout << "\nOriginal matrix:";
printMatrix (matr, m);

int neg = 0, pos = 0, maxneg = 0, maxpos = 0, mni = m-1, mpi = 0;
for (int i=0; i<m; i++) {
neg = 0; pos = 0;
for (int j=0; j<matr[i].cr; j++) {
if (matr[i].row[j]>0) pos++;
else if (matr[i].row[j]<0) neg++;
}
if (pos>maxpos) {maxpos = pos; mpi = i;}
if (neg>maxneg) {maxneg = neg; mni = i;}
}
if (mni == m-1 || mpi == 0) cout << "/nNot all rows need to be exchanged/n";
if (mni == mpi) {cout << "/nNegative row = positive row, exit"; _getch(); return 0;}

int *buf;
buf = matr[0].row;
cr = matr[0].cr;
matr[0].row = matr[mpi].row;
matr[0].cr = matr[mpi].cr;
matr[mpi].row = buf;
matr[mpi].cr = cr;

if (mni==0) mni = mpi;

buf = matr[m-1].row;
cr = matr[m-1].cr;
matr[m-1].row = matr[mni].row;
matr[m-1].cr = matr[mni].cr;
matr[mni].row = buf;
matr[mni].cr = cr;

cout << "\nNew matrix:";
printMatrix (matr, m);

for (int i=0; i<m; i++) delete [] matr[i].row;
delete [] matr;

_getch();
return 0;
}
[/code]
давно
Посетитель
276566
297
18.02.2011, 16:17
общий
В функции main не должно происходить ни каких вычислений только вызов функций которые выполняют то или иное действие
Неизвестный
18.02.2011, 16:20
общий
Адресаты:
Вынести в функцию - не проблема. Вопрос в логике решения: Вам нужна такая, как у vladisslav, или такая, как в моём примере? У него матрица строго MxN элементов, у меня - ряды переменной длины.
Неизвестный
18.02.2011, 16:37
общий
это ответ
Здравствуйте, Magma!
Программа. С++.
Код:
#include <iostream>
#include <stdexcept>
#include <locale>

// Тип данных с которым будем работать. По условию int.
typedef int data_t;

// Класс - массив

template<class T>
class array
{
public:
// Конструкторы/деструктор
array(size_t count = 0);
array(const array<T>& r);
virtual ~array();
// Оператор присваивания
const array<T> & operator=(const array<T>& r);
// Изменение размера
void resize(size_t count);
// Размер
size_t size() const;
// Индексация массива
T & operator[](size_t index);
const T & operator[](size_t index) const;
private:
void copy(const array<T>& r);
void destroy();
size_t _size;
T* _data;
};

// Оператор вывода

template<class char_t, class traits_t, class T>
std::basic_ostream<char_t, traits_t> & operator<<(std::basic_ostream<char_t, traits_t>& stream, const array<T>& right)
{
const std::ctype<char_t>& facet = std::use_facet< std::ctype<char_t> >(stream.getloc());
for (size_t i = 0, end = right.size(); i < end; ++i)
{
stream << facet.widen(' ') << right[i];
}
return stream << std::endl;
}

// Используем для ввода данных

template<class T> T input()
{
T result = T();
std::cin >> result;
if (std::cin.fail())
{
throw std::runtime_error("Ошибка ввода");
}
return result;
}

/*
*
*/
int main(int argc, char** argv)
{
try
{
std::locale::global(std::locale(""));

// Ввод данных
array< array<data_t> > matr(input<size_t > ());

for (size_t row = 0, end = matr.size(); row < end; ++row)
{
matr[row].resize(input<size_t > ());
for (size_t col = 0, end = matr[row].size(); col < end; ++col)
{
matr[row][col] = input<data_t > ();
}
}

// Выведем для проверки
std::cout << "Исходная матрица: " << std::endl << matr;

// Ищем максимум пложительных/отрицательных
size_t maxPositive = 0, maxNegative = 0, maxPositiveRow = 0, maxNegativeRow = 0;
for (size_t row = 0, end = matr.size(); row < end; ++row)
{
size_t positive = 0, negative = 0;
for (size_t col = 0, end = matr[row].size(); col < end; ++col)
{
positive += matr[row][col] > 0;
negative += matr[row][col] < 0;
}
if (positive > maxPositive)
{
maxPositive = positive;
maxPositiveRow = row;
}
if (negative > maxNegative)
{
maxNegative = negative;
maxNegativeRow = row;
}
}

std::cout << "Строка, содержащая максимальное к-во положительных - " << maxPositiveRow << ", отрицательных - " << maxNegativeRow << std::endl;

// Осуществляем обмен согласно условия
std::swap(matr[0], matr[maxPositiveRow]);
if (maxNegativeRow == 0)
{
maxNegativeRow = maxPositiveRow;
}
else if (maxNegativeRow == maxPositiveRow)
{
maxNegativeRow = 0;
}
std::swap(matr[maxNegativeRow], matr[matr.size() - 1]);

// Выводим результат
std::cout << "Результат: " << std::endl << matr;
}
catch (std::exception& ex)
{
std::cerr << ex.what() << std::endl;
}

#ifdef _WIN32
std::system("pause");
#endif

return 0;
}

template<class T>
array<T>::array(size_t count)
: _data(0)
, _size(0)
{
try
{
_data = new T[count];
_size = count;
}
catch (std::bad_alloc&)
{
throw std::runtime_error("Не могу выделить память");
}
}

template<class T>
array<T>::~array()
{
destroy();
}

template<class T>
array<T>::array(const array<T>& r)
: _data(0)
, _size(0)
{
copy(r);
}

template<class T>
const array<T>& array<T>::operator =(const array<T>& r)
{
copy(r);
return *this;
}

template<class T>
void array<T>::copy(const array<T>& r)
{
if (this == &r)
{
return;
}

try
{
destroy();
_data = new T[r._size];
_size = r._size;
for (size_t i = 0; i < _size; ++i)
{
_data[i] = r._data[i];
}
}
catch (std::bad_alloc&)
{
throw std::runtime_error("Не могу выделить память");
}
}

template<class T>
void array<T>::destroy()
{
if (_data)
{
delete[] _data;
_size = 0;
_data = 0;
}
}

template<class T>
void array<T>::resize(size_t count)
{
try
{
T* newData = new T[count];
for (size_t i = 0, end = std::min(_size, count); i < end; ++i)
{
newData[i] = _data[i];
}
delete[] _data;
_size = count;
_data = newData;
}
catch (std::bad_alloc&)
{
throw std::runtime_error("Не могу выделить память");
}
}

template<class T>
size_t array<T>::size() const
{
return _size;
};

template<class T>
T& array<T>::operator [](size_t index)
{
if (index < _size)
{
return _data[index];
}
throw std::runtime_error("Выход за пределы диапазона");
}

template<class T>
const T& array<T>::operator [](size_t index) const
{
if (index < _size)
{
return _data[index];
}
throw std::runtime_error("Выход за пределы диапазона");
}

Пример исходных данных(файл test.txt)
Код:
5
3
-5 1 4
4
-10 11 -3 -5
3
1 2 4
1
-1
6
-1 -2 -3 4 4 5

Формат исходных данных:
Количество строк. Далее перед каждой строкой количество элементов в этой строке, далее сами элементы и т.д.
Результат работы:
Код:
>182246.exe < test.txt
Исходная матрица:
-5 1 4
-10 11 -3 -5
1 2 4
-1
-1 -2 -3 4 4 5

Строка, содержащая максимальное к-во положительных - 2, отрицательных - 1
Результат:
1 2 4
-1 -2 -3 4 4 5
-5 1 4
-1
-10 11 -3 -5

Неизвестный
18.02.2011, 17:10
общий
Цитата: 256539
Из входного потока вводится непрямоугольная матрица целых чисел

Благодарю.
Исправил. Вынес все в функции. Использовал структуру, как сказано в задании.
Входной файл:
1-ая строка - количество строк матрицы
последующие строки - 1-ое число - количество элементов, далее элементы.
Код:
#include <iostream>
#include <vector>

using namespace std;

typedef vector <int> vi;
struct context
{
int m,n,//row count, column count
count_neg,count_pos,//value counters
num_neg,num_pos;//row positions
vector <vi> arr;
vector <vi> res;
};

void input_data(struct context &c)
{
int i,j;
c.m=0;c.n=0;
c.count_neg=0;c.count_pos=0;
c.num_neg=0;c.num_pos=0;
cin>>c.n;
//source matrix
c.arr=vector <vi> (c.n);
for(j=0;j<c.n;j++)
{
//local counts and a value buffer
int loc_count_neg=0,loc_count_pos=0,loc_val=0;
cin>>c.m;
c.arr[j]=vi(c.m);
for(i=0;i<c.m;i++)
{
//input and count values
cin >> loc_val;
c.arr[j][i]=loc_val;
if(loc_val>0)++loc_count_pos;
if(loc_val<0)++loc_count_neg;
}
//check against previous and replace
if(loc_count_neg>c.count_neg)
{
c.count_neg=loc_count_neg;
c.num_neg=j;
}
if(loc_count_pos>c.count_pos)
{
c.count_pos=loc_count_pos;
c.num_pos=j;
}
}
}

void print_data(vector <vi> arr, string msg)
{
int i,j;
cout<<msg<<endl;
for(j=0;j<arr.size();j++)
{
for(i=0;i<arr[j].size();i++)
cout<<arr[j][i]<<" ";
cout<<endl;
}
}

void real_main(struct context &c)
{
int i,j;
c.res=vector <vi>(c.n);
if((c.num_pos == c.n-1) && (c.num_neg == 0))
{
//Both are on oppsite ends. Just swap them.
c.res[0]=c.arr[c.num_pos];
c.res[c.n-1]=c.arr[c.num_neg];
}else if(c.num_pos==c.num_neg)
{
//Oops both are on the same line.
cout<<"Failed."<<endl<<
"Max negative row == max positive row"<<endl;
exit(1);
}else if(c.num_neg==0)
{
//max negative is on the first line
//Swap it first to avoid overwriting
c.res[c.n-1]=c.arr[c.num_neg];
c.res[c.num_neg]=c.arr[c.n-1];
c.res[0]=c.arr[c.num_pos];
c.res[c.num_pos]=c.arr[0];
}else{
//"generic" swap
c.res[0]=c.arr[c.num_pos];
c.res[c.num_pos]=c.arr[0];
c.res[c.n-1]=c.arr[c.num_neg];
c.res[c.num_neg]=c.arr[c.n-1];
}
for(j=1;j<c.n-1;j++)
{
if((j!=c.num_pos) && (j!=c.num_neg))
c.res[j]=c.arr[j];
}
}




int main()
{
struct context ctx;
input_data(ctx);
real_main(ctx);
print_data(ctx.arr,"Source matrix");
print_data(ctx.res,"Result matrix");
return 0;

}

Тестирование:
Код:
$ for ((k=1;k<=4;k++)); do echo test$k ; cat test$k ; echo ""; ./t<test$k ; done
test1
5
6 1 -2 -3 -4 -5 -6
5 2 -4 6 -3 2
7 3 3 3 3 -4 0 11
4 2 -2 -6 4
5 2 3 4 5 9

Source matrix
1 -2 -3 -4 -5 -6
2 -4 6 -3 2
3 3 3 3 -4 0 11
2 -2 -6 4
2 3 4 5 9
Result matrix
3 3 3 3 -4 0 11
2 -4 6 -3 2
1 -2 -3 -4 -5 -6
2 -2 -6 4
1 -2 -3 -4 -5 -6
test2
4
7 0 0 0 0 0 0 0
4 -4 6 -3 2
4 0 0 0 0
3 0 0 0

Failed.
Max negative row == max positive row
test3
5
4 -2 -3 -4 -5
4 -4 6 -3 2
4 2 3 4 5
4 3 3 3 -4
4 2 -2 -6 4

Source matrix
-2 -3 -4 -5
-4 6 -3 2
2 3 4 5
3 3 3 -4
2 -2 -6 4
Result matrix
2 3 4 5
-4 6 -3 2
-2 -3 -4 -5
3 3 3 -4
-2 -3 -4 -5
test4
5
5 1 -4 6 -3 2
6 2 -2 -3 -4 -5 -9
7 3 2 3 4 5 6 7
4 3 3 3 -4
5 2 -2 -6 4 5

Source matrix
1 -4 6 -3 2
2 -2 -3 -4 -5 -9
3 2 3 4 5 6 7
3 3 3 -4
2 -2 -6 4 5
Result matrix
3 2 3 4 5 6 7
2 -2 -6 4 5
1 -4 6 -3 2
3 3 3 -4
2 -2 -3 -4 -5 -9
Неизвестный
18.02.2011, 18:07
общий
Чего как ответ не оформляете?
давно
Посетитель
276566
297
19.02.2011, 20:22
общий
Здравствуйте! Нормально, но есть дополнительное условие: матрица должна задаваться одним из трех вариантов(int *a[10]; int (*a)[10]; int **a), память должна выделяться динамически с помощью оператора new и удаляться с помощью оператора delete.
Неизвестный
19.02.2011, 20:41
общий
Адресаты:
Цитата: Maverick
матрица должна задаваться одним из трех вариантов(int *a[10]; int (*a)[10]; int **a), память должна выделяться динамически с помощью оператора new и удаляться с помощью оператора delete.

Здесь подходит только вариант int ** a, так как размеры неизвестны заранее.
Код:
#include <iostream>

using namespace std;

struct context
{
int m,n,//row count, column count
count_neg,count_pos,//value counters
num_neg,num_pos;//row positions
int ** arr;
int ** res;
};

void input_data(struct context &c)
{
int i,j;
c.m=0;c.n=0;
c.count_neg=0;c.count_pos=0;
c.num_neg=0;c.num_pos=0;
cin>>c.n;
//source matrix
c.arr=new int*[c.n];
for(j=0;j<c.n;j++)
{
//local counts and a value buffer
int loc_count_neg=0,loc_count_pos=0,loc_val=0;
cin>>c.m;
c.arr[j]=new int[c.m+1];
c.arr[j][0]=c.m;
for(i=1;i<=c.m;i++)
{
//input and count values
cin >> loc_val;
c.arr[j][i]=loc_val;
if(loc_val>0)++loc_count_pos;
if(loc_val<0)++loc_count_neg;
}
//check against previous and replace
if(loc_count_neg>c.count_neg)
{
c.count_neg=loc_count_neg;
c.num_neg=j;
}
if(loc_count_pos>c.count_pos)
{
c.count_pos=loc_count_pos;
c.num_pos=j;
}
}
}

void print_data(int ** arr,int size, string msg)
{
int i,j;
cout<<msg<<endl;
for(j=0;j<size;j++)
{
for(i=1;i<=arr[j][0];i++)
cout<<arr[j][i]<<" ";
cout<<endl;
}
}

void real_main(struct context &c)
{
int i,j;
c.res=new int *[c.n];
if((c.num_pos == c.n-1) && (c.num_neg == 0))
{
//Both are on oppsite ends. Just swap them.
c.res[0]=c.arr[c.num_pos];
c.res[c.n-1]=c.arr[c.num_neg];
}else if(c.num_pos==c.num_neg)
{
//Oops both are on the same line.
cout<<"Failed."<<endl<<
"Max negative row == max positive row"<<endl;
exit(1);
}else if(c.num_neg==0)
{
//max negative is on the first line
//Swap it first to avoid overwriting
c.res[c.n-1]=c.arr[c.num_neg];
c.res[c.num_neg]=c.arr[c.n-1];
c.res[0]=c.arr[c.num_pos];
c.res[c.num_pos]=c.arr[0];
}else{
//"generic" swap
c.res[0]=c.arr[c.num_pos];
c.res[c.num_pos]=c.arr[0];
c.res[c.n-1]=c.arr[c.num_neg];
c.res[c.num_neg]=c.arr[c.n-1];
}
for(j=1;j<c.n-1;j++)
{
if((j!=c.num_pos) && (j!=c.num_neg))
c.res[j]=c.arr[j];
}
}

void free_data(struct context &ctx)
{
int k;
for(k=0;k<ctx.n;k++)
delete [] ctx.arr[k];
delete [] ctx.arr;
delete [] ctx.res;
}


int main()
{
struct context ctx;
input_data(ctx);
real_main(ctx);
print_data(ctx.arr,ctx.n,"Source matrix");
print_data(ctx.res,ctx.n,"Result matrix");
free_data(ctx);
return 0;

}

Проверка:
Код:
$ for ((k=1;k<=4;k++)); do echo test$k ; cat test$k ; echo ""; ./t<test$k ; done
test1
5
6 1 -2 -3 -4 -5 -6
5 2 -4 6 -3 2
7 3 3 3 3 -4 0 11
4 2 -2 -6 4
5 2 3 4 5 9

Source matrix
1 -2 -3 -4 -5 -6
2 -4 6 -3 2
3 3 3 3 -4 0 11
2 -2 -6 4
2 3 4 5 9
Result matrix
3 3 3 3 -4 0 11
2 -4 6 -3 2
1 -2 -3 -4 -5 -6
2 -2 -6 4
1 -2 -3 -4 -5 -6
test2
4
7 0 0 0 0 0 0 0
4 -4 6 -3 2
4 0 0 0 0
3 0 0 0

Failed.
Max negative row == max positive row
test3
5
4 -2 -3 -4 -5
4 -4 6 -3 2
4 2 3 4 5
4 3 3 3 -4
4 2 -2 -6 4

Source matrix
-2 -3 -4 -5
-4 6 -3 2
2 3 4 5
3 3 3 -4
2 -2 -6 4
Result matrix
2 3 4 5
-4 6 -3 2
-2 -3 -4 -5
3 3 3 -4
-2 -3 -4 -5
test4
5
5 1 -4 6 -3 2
6 2 -2 -3 -4 -5 -9
7 3 2 3 4 5 6 7
4 3 3 3 -4
5 2 -2 -6 4 5

Source matrix
1 -4 6 -3 2
2 -2 -3 -4 -5 -9
3 2 3 4 5 6 7
3 3 3 -4
2 -2 -6 4 5
Result matrix
3 2 3 4 5 6 7
2 -2 -6 4 5
1 -4 6 -3 2
3 3 3 -4
2 -2 -3 -4 -5 -9


Если все устраивает, делаю ответ.
давно
Посетитель
276566
297
19.02.2011, 21:10
общий
Здравствуйте! Ваш код подходит, но не могли бы вы его представить в виде структур типа:
void input()
{
ввод данных
}

void work()
{
выполнение поставленного условия
}

void output()
{
вывод данных
}

int main()
{
только вызов функций
}
Неизвестный
19.02.2011, 21:46
общий
это ответ
Здравствуйте, Magma!
Вариант без классов, с использованием структуры для хранения ряда матрицы. Проверено на VS 2005, но должно работать и в Builder.
Удачи!

Приложение:
#include <conio.h>
#include <iostream>
using namespace std;

struct elem { //ряд разреженной матрицы
int cr; //число элементов ряда
int* row; //ряд
};

void printMatrix (elem* matr, int m) //вывод на экран
{
for (int i=0; i<m; i++) {
cout << endl;
for (int j=0; j<matr[i].cr; j++)
cout << matr[i].row[j] << ' ';
}
}

elem* Input (int &m, int &n) //ввод данных (возвращает матрицу)
{
int cr;
elem* matr = NULL;

cout << "Enter m: ";
cin >> m;
cout << "Enter n: ";
cin >> n;

matr = new elem [m];

for (int i=0; i<m; i++) {
cout << "Enter count for row " << i << ", <=" << n << ": ";
cin >> cr;
while (cr<=0 || cr>n) { //проверяем число элементов ряда на соответствие
cout << "/nError! Reenter: ";
cin >> cr;
}
matr[i].cr = cr;
matr[i].row = new int [cr];
cout << "Enter elements:\n";
for (int j=0; j<cr; j++)
cin >> matr[i].row[j];
}
return matr;
}

void Make (elem* matr, int m, int n) //обработка по заданию
{
int neg = 0, pos = 0, maxneg = 0, maxpos = 0, mni = m-1, mpi = 0, cr;
for (int i=0; i<m; i++) { //подсчёт
neg = 0; pos = 0;
for (int j=0; j<matr[i].cr; j++) {
if (matr[i].row[j]>0) pos++;
else if (matr[i].row[j]<0) neg++;
}
if (pos>maxpos) {maxpos = pos; mpi = i;} //выбор максимальных
if (neg>maxneg) {maxneg = neg; mni = i;}
}
if (mni == m-1 || mpi == 0) cout << "/nNot all rows need to be exchanged/n";
if (mni == mpi) {cout << "/nNegative row = positive row, exit"; _getch(); return;}

int *buf; //обмен через буфер для ряда
buf = matr[0].row;
cr = matr[0].cr;
matr[0].row = matr[mpi].row;
matr[0].cr = matr[mpi].cr;
matr[mpi].row = buf;
matr[mpi].cr = cr;

if (mni==0) mni = mpi;

buf = matr[m-1].row;
cr = matr[m-1].cr;
matr[m-1].row = matr[mni].row;
matr[m-1].cr = matr[mni].cr;
matr[mni].row = buf;
matr[mni].cr = cr;
}

void Clear (elem* matr, int m) //очистка памяти
{
for (int i=0; i<m; i++) delete [] matr[i].row;
delete [] matr;
}

int main(void)
{
int m,n,cr;
elem* matr = Input (m, n); //ввод

cout << "\nOriginal matrix:";
printMatrix (matr, m); //вывод исходной

Make (matr, m, n); //обработка

cout << "\nNew matrix:";
printMatrix (matr, m); //вывод обработанной

Clear (matr, m); //очистка

_getch();
return 0;
}
Неизвестный
20.02.2011, 14:16
общий
это ответ
Здравствуйте, Magma!
Используется структура. Данные хранятся в массиве указателей. Количество элементов в массивах второго уровня хранится в первом элементе (с индексом 0).
Память освобождается явным образом.
Судя по тестам вроде работает
проверка:
Код:
$ for ((k=1;k<=4;k++)); do echo test$k ; cat test$k ; echo ""; ./t<test$k ; done
test1
5
6 1 -2 -3 -4 -5 -6
5 2 -4 6 -3 2
7 3 3 3 3 -4 0 11
4 2 -2 -6 4
5 2 3 4 5 9

Source matrix
1 -2 -3 -4 -5 -6
2 -4 6 -3 2
3 3 3 3 -4 0 11
2 -2 -6 4
2 3 4 5 9
Result matrix
3 3 3 3 -4 0 11
2 -4 6 -3 2
1 -2 -3 -4 -5 -6
2 -2 -6 4
1 -2 -3 -4 -5 -6
test2
4
7 0 0 0 0 0 0 0
4 -4 6 -3 2
4 0 0 0 0
3 0 0 0

Failed.
Max negative row == max positive row
test3
5
4 -2 -3 -4 -5
4 -4 6 -3 2
4 2 3 4 5
4 3 3 3 -4
4 2 -2 -6 4

Source matrix
-2 -3 -4 -5
-4 6 -3 2
2 3 4 5
3 3 3 -4
2 -2 -6 4
Result matrix
2 3 4 5
-4 6 -3 2
-2 -3 -4 -5
3 3 3 -4
-2 -3 -4 -5
test4
5
5 1 -4 6 -3 2
6 2 -2 -3 -4 -5 -9
7 3 2 3 4 5 6 7
4 3 3 3 -4
5 2 -2 -6 4 5

Source matrix
1 -4 6 -3 2
2 -2 -3 -4 -5 -9
3 2 3 4 5 6 7
3 3 3 -4
2 -2 -6 4 5
Result matrix
3 2 3 4 5 6 7
2 -2 -6 4 5
1 -4 6 -3 2
3 3 3 -4
2 -2 -3 -4 -5 -9


Приложение:
#include <iostream>

using namespace std;

struct context
{
int m,n,//row count, column count
count_neg,count_pos,//value counters
num_neg,num_pos;//row positions
int ** arr;//source matrix
int ** res;//result matrix
};

void input_data(struct context &c)
{
int i,j;
c.m=0;c.n=0;
c.count_neg=0;c.count_pos=0;
c.num_neg=0;c.num_pos=0;
cin>>c.n;
//source matrix
c.arr=new int*[c.n];
for(j=0;j<c.n;j++)
{
//local counts and a value buffer
int loc_count_neg=0,loc_count_pos=0,loc_val=0;
cin>>c.m;
c.arr[j]=new int[c.m+1];
c.arr[j][0]=c.m;
for(i=1;i<=c.m;i++)
{
//input and count values
cin >> loc_val;
c.arr[j][i]=loc_val;
if(loc_val>0)++loc_count_pos;
if(loc_val<0)++loc_count_neg;
}
//check against previous and replace
if(loc_count_neg>c.count_neg)
{
c.count_neg=loc_count_neg;
c.num_neg=j;
}
if(loc_count_pos>c.count_pos)
{
c.count_pos=loc_count_pos;
c.num_pos=j;
}
}
}

void print_data(int ** arr,int size, string msg)
{
int i,j;
//output message
cout<<msg<<endl;
//loop over all elements
for(j=0;j<size;j++)
{
for(i=1;i<=arr[j][0];i++)
cout<<arr[j][i]<<" ";
cout<<endl;
}
}

void real_main(struct context &c)
{
int i,j;
c.res=new int *[c.n];
if((c.num_pos == c.n-1) && (c.num_neg == 0))
{
//Both are on oppsite ends. Just swap them.
c.res[0]=c.arr[c.num_pos];
c.res[c.n-1]=c.arr[c.num_neg];
}else if(c.num_pos==c.num_neg)
{
//Oops both are on the same line.
cout<<"Failed."<<endl<<
"Max negative row == max positive row"<<endl;
exit(1);
}else if(c.num_neg==0)
{
//max negative is on the first line
//Swap it first to avoid overwriting
c.res[c.n-1]=c.arr[c.num_neg];
c.res[c.num_neg]=c.arr[c.n-1];
c.res[0]=c.arr[c.num_pos];
c.res[c.num_pos]=c.arr[0];
}else{
//"generic" swap
c.res[0]=c.arr[c.num_pos];
c.res[c.num_pos]=c.arr[0];
c.res[c.n-1]=c.arr[c.num_neg];
c.res[c.num_neg]=c.arr[c.n-1];
}
for(j=1;j<c.n-1;j++)
{
if((j!=c.num_pos) && (j!=c.num_neg))
c.res[j]=c.arr[j];
}
}

void free_data(struct context &ctx)
{
int k;
for(k=0;k<ctx.n;k++)
delete [] ctx.arr[k];
delete [] ctx.arr;
delete [] ctx.res;
}


int main()
{
struct context ctx;
input_data(ctx);
real_main(ctx);
print_data(ctx.arr,ctx.n,"Source matrix");
print_data(ctx.res,ctx.n,"Result matrix");
free_data(ctx);
return 0;

}
Форма ответа