Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <stdio.h>
- #include <stdlib.h>
- #include <stdbool.h>
- typedef long long int llint;
- int **allocMat(int rows, int cols) {
- int **mat = (int**)malloc(sizeof(int*) * rows);
- for (int i = 0; i < rows; i++) {
- mat[i] = (int*)malloc(sizeof(int) * cols);
- }
- return mat;
- }
- void readMatElems(int **mat, int rows, int cols) {
- for (int i = 0; i < rows; i++) {
- for (int j = 0; j < cols; j++) {
- scanf("%d", &mat[i][j]);
- }
- }
- }
- int **readMat(int *rows, int *cols) {
- scanf("%d %d", rows, cols);
- int **mat = allocMat(*rows, *cols);
- readMatElems(mat, *rows, *cols);
- return mat;
- }
- llint sumOnRow(int **mat, int targetRow, int cols) {
- llint sum = 0;
- for (int j = 0; j < cols; j++) {
- sum += mat[targetRow][j];
- }
- return sum;
- }
- void sortMatLines(int **mat, int rows, int cols) {
- bool sorted;
- do {
- sorted = true;
- for (int i = 1; i < rows; i++) {
- if (sumOnRow(mat, i - 1, cols) > sumOnRow(mat, i, cols)) {
- int *aux = mat[i - 1];
- mat[i - 1] = mat[i];
- mat[i] = aux;
- sorted = false;
- }
- }
- } while(!sorted);
- }
- llint sumOnCol(int **mat, int targetCol, int rows) {
- llint sum = 0;
- for (int i = 0; i < rows; i++) {
- sum += mat[i][targetCol];
- }
- return sum;
- }
- bool colsSorted(int **mat, int rows, int cols) {
- for (int j = 1; j < cols; j++) {
- if (sumOnCol(mat, j - 1, rows) > sumOnCol(mat, j, rows)) {
- return false;
- }
- }
- return true;
- }
- void displayMat(int **mat, int rows, int cols) {
- for (int i = 0; i < rows; i++) {
- for (int j = 0; j < cols; j++) {
- printf("%d ", mat[i][j]);
- }
- printf("\n");
- }
- }
- void freeMat(int **mat, int rows, int cols) {
- for (int i = 0; i < rows; i++) {
- free(mat[i]);
- }
- free(mat);
- }
- int main(void) {
- int rows, cols, **mat = NULL;
- mat = readMat(&rows, &cols);
- sortMatLines(mat, rows, cols);
- puts("");
- displayMat(mat, rows, cols);
- printf("columns sorted: %s\n", (colsSorted(mat, rows, cols) ? "true" : "false"));
- freeMat(mat, rows, cols);
- return 0;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement