#include<stdio.h>
#include<stdlib.h>
typedef struct {
    int* row;
    int sum;
}Rowwithsum;
int compareRows(const void* a, const void* b){
    Rowwithsum* rowA = (Rowwithsum*)a;
    Rowwithsum* rowB = (Rowwithsum*)b;
    return row->sum - rowB->sum;
}
int main(){
    int m,n;
    scanf("%d %d", &m, &n);
    if(m <= 0 || n <= 0){
        printf("Invalid input\n");
        return 0;
    }
    Rowwithsum* rows = (Rowwithsum*)malloc(m * sizeof(Rowwithsum));
    if(rows == NULL){
        return 1;
    }
    for(int i = 0; i < m; i++){
        rows[i].row = (int*)malloc(n * sizeof(int));
        if(row[i].row == NULL){
            for(int j = 0; j < i; j++){
                free(rows[j].row);
            }
            free(rows);
            return 1;
        }
        rows[i].sum = 0;
        for(int j = 0; j < n; j++){
            scanf("%d", &rows[i]. row[j]);
            rows[i].sum += rows[i].row[j];
        }
    }
    qsort(rows, m, sizeof(Rowwithsum), compareRows);
    for(int i = 0; i < m; i++){
        for(int j = 0; j < n; j++){
            printf("%d ", rows[i].row[j]);
        }
        printf("\n");
    }
    for(int i = 0; i < m; i++){
        free(rows[i].row);
    }
    
        free(rows);
    return 0;
}