#include #include #include bool readMatrix(double **a, int *n, int *m); double compareRows(const double *a, int n, int m, int i1, int i2); double rowNorm(const double *a, int n, int m, int i); void sortRows(double *a, int n, int m); void swapRows(double *a, int n, int m, int i1, int i2); int main() { double *a; // Matrix array int n, m; // rows, columns if (!readMatrix(&a, &n, &m)) return (-1); sortRows(a, n, m); // Multiply the changed matrix to its transposed last row double *c = new double[n]; // Output vector const double *b = a + (n-1)*m; // The last row of matrix a for (int i = 0; i < n; ++i) { c[i] = 0.; for (int k = 0; k < m; ++k) { c[i] += a[i*m + k]*b[k]; } } // Write the results in the file "output.txt" FILE *out = fopen("output.txt", "wt"); if (out == NULL) { perror("Cannot open the output file"); delete[] a; delete[] c; return (-1); } fprintf(out, "%d %d\n", n, m); for (int i = 0; i < n; ++i) { for (int j = 0; j < m; ++j) { fprintf(out, "%f ", a[i*m + j]); } fprintf(out, "\n"); } fprintf(out, "\n"); for (int j = 0; j < n; ++j) { fprintf(out, "%f ", c[j]); } fprintf(out, "\n"); fclose(out); delete[] a; delete[] c; return 0; } bool readMatrix(double **a, int *n, int *m) { FILE *in = fopen("input.txt", "rt"); if (in == NULL) { perror("Cannot open the input file"); return false; } int rows, cols; if ( fscanf(in, "%d%d", &rows, &cols) < 2 || rows <= 0 || cols <= 0 ) { fprintf(stderr, "Incorrect input file.\n"); fclose(in); return false; } double *matr = new double[rows*cols]; for (int i = 0; i < rows; ++i) { for (int j = 0; j < cols; ++j) { if (fscanf(in, "%lf", &(matr[i*cols + j])) < 1) { fprintf(stderr, "Incorrect input file.\n"); delete[] matr; return false; } } } fclose(in); *a = matr; *n = rows; *m = cols; return true; } double compareRows(const double *a, int n, int m, int i1, int i2) { double s1 = rowNorm(a, n, m, i1); double s2 = rowNorm(a, n, m, i2); return (s1 - s2); } double rowNorm(const double *a, int n, int m, int i) { assert(0 <= i && i < n); double s = 0.; for (int j = 0; j < m; ++j) { double d = a[i*m + j]; s += d*d; } return s; } void sortRows(double *a, int n, int m) { // Using the Insertion Sort algorithm int k = 0; // Number of already sorted rows while (k < n) { int row = k; // The first unsorted row while (row > 0) { if (compareRows(a, n, m, row-1, row) <= 0.) break; // Ok! swapRows(a, n, m, row-1, row); --row; } ++k; } } void swapRows(double *a, int n, int m, int i1, int i2) { assert(0 <= i1 && i1 < n); assert(0 <= i2 && i2 < n); for (int j = 0; j < m; ++j) { double tmp = a[i1*m + j]; a[i1*m + j] = a[i2*m + j]; a[i2*m + j] = tmp; } }