#include #include bool readMatrix(double **a, int *n, int *m); double compareCols(const double *a, int n, int m, int j1, int j2); double columnWeight(const double *a, int n, int m, int j); void sortCols(double *a, int n, int m); void swapCols(double *a, int n, int m, int j1, int j2); int main() { double *a; // Matrix array int n, m; // rows, columns if (!readMatrix(&a, &n, &m)) return (-1); sortCols(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 compareCols(const double *a, int n, int m, int j1, int j2) { double w1 = columnWeight(a, n, m, j1); double w2 = columnWeight(a, n, m, j2); return (w2 - w1); // Sic! Sorting in descending order } double columnWeight(const double *a, int n, int m, int j) { double w = 0.; for (int i = 0; i < n-1; ++i) { w += fabs(a[i*m + j] - a[(i+1)*m + j]); } return w; } void sortCols(double *a, int n, int m) { // Using the Insertion Sort algorithm int k = 0; // Number of already sorted columns while (k < m) { int col = k; // The first unsorted column while (col > 0) { if (compareCols(a, n, m, col-1, col) <= 0.) break; // Ok! swapCols(a, n, m, col-1, col); --col; } ++k; } } void swapCols(double *a, int n, int m, int j1, int j2) { for (int i = 0; i < n; ++i) { double tmp = a[i*m + j1]; a[i*m + j1] = a[i*m + j2]; a[i*m + j2] = tmp; } }