Matrix76. Дана матрица размера M × N. Упорядочить ее строки так, чтобы их первые элементы образовывали возрастающую последовательность.
>Решение Pascal
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 | program Matrix76; type matrix = array [1..10,1..10] of integer; var a:matrix; M, M2, N, i, i2, j:Integer; procedure Swap(var X,Y:Integer); begin if x<>y then begin X:=X+Y; Y:=X-Y; X:=X-Y; end; end; procedure SwapMatrixRow(var mat:matrix; X,Y:Integer); var j:integer; begin if x<>y then for j:=1 to N do swap(mat[x,j], mat[y,j]); end; begin Write('N: '); Readln(N); Write('M: '); Readln(M); for i:=1 to M do begin writeln(i,': '); for j:=1 to N do begin Write(j,' : '); Read(a[i,j]); end; end; M2:=M; for i:=1 to M-1 do begin i2:=1; M2:=M2-1; while (i2<=M2) do begin if a[i2,1]>a[i2+1,1] then begin SwapMatrixRow(a, i2, i2+1); end; inc(i2); end; end; for i:=1 to M do begin for j:=1 to N do begin Write(' : ',a[i,j]); end; writeln(' : '); end; end. |
Решение C++ (1)
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 | #include <iostream> using namespace std; int N; void Swap(int& x, int& y){ if (x!=y){ x=x+y; y=x-y; x=x-y; } } void SwapMatrixRow (int mat[10][10], int x, int y){ int j; if (x!=y) for (j=1;j<=N; ++j) Swap(mat[x][j],mat[y][j]); } int main(int argc, char *argv[]) { cout << "N: "; cin >> N; int m; cout << "M: "; cin >> m; int a[10][10]; int i,j; for (i=1; i<=m; ++i){ cout<<i<<" : "<<endl; for (j=1; j<=N; ++j){ cout<<j<<" : "; cin >> a[i][j]; } } int m2=m,i2; for (i=1; i<m; ++i){ i2=1; --m2; while (i2<=m2){ if (a[i2][1]>a[i2+1][1]) SwapMatrixRow(a, i2, i2+1); ++i2; } } for (i=1; i<=m; ++i){ for (j=1; j<=N; ++j){ cout<<" : "<<a[i][j]; } cout<<" : "<<endl; } return 0; } |
Решение C++ (2)
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 | #include <iostream> using namespace std; int main(int argc, char *argv[]) { int m, n; cout << "N: "; cin >> n; cout << "M: "; cin >> m; int a[10][10]; int i,j; for (i=1; i<=m; ++i){ cout<<i<<" : "<<endl; for (j=1; j<=n; ++j){ cout<<j<<" : "; cin >> a[i][j]; } } int m2=m,i2; for (i=1; i<m; ++i){ i2=1; --m2; while (i2<=m2){ if (a[i2][1]>a[i2+1][1]) for (j=1;j<=n; ++j) { a[i2][j]+=a[i2+1][j]; a[i2+1][j]=a[i2][j]-a[i2+1][j]; a[i2][j]=a[i2][j]-a[i2+1][j]; } ++i2; } } for (i=1; i<=m; ++i){ for (j=1; j<=n; ++j){ cout<<" : "<<a[i][j]; } cout<<" : "<<endl; } return 0; } |