Cho ma trận NxM, in chỉ số các cột (bắt đầu từ 1) sau khi sắp xếp tăng dần theo số lượng số 0 trong mỗi cột.
Ví dụ
Input:
0 0 0
1 1 1
1 0 1
Output: 1 3 2

Giải thích: Cột 1 có 1 số 0, cột 2 có 0 số 0, cột 3 có 2 số 0 -> sắp xếp: cột 2 (0), cột 1 (1), cột 3 (2) -> chỉ số: 2 1 3? Wait, ví dụ output là 1 3 2. Kiểm tra lại: Cột 1: [0,1,1] -> 1 zero. Cột 2: [0,1,0] -> 2 zeros. Cột 3: [0,1,1] -> 1 zero. Sắp xếp: cột 1 (1), cột 3 (1), cột 2 (2) -> 1 3 2. Đúng.
Chương trình C++ ví dụ
#include <bits/stdc++.h>
#define row 3
#define col 3
using namespace std;
void sorting(int arr[row][col]) {
vector> count_zero;
for (int i = 0; i < col; i++) {
int count = 0;
for (int j = 0; j < row; j++)
if (arr[j][i] == 0) count++;
count_zero.push_back({count, i});
}
sort(count_zero.begin(), count_zero.end());
for (int i = 0; i < col; i++)
cout << count_zero[i].second + 1 << " ";
}
int main() {
int array[row][col] = {{0,0,0}, {1,1,1}, {1,0,1}};
cout << "sorted order of zeroes count is: ";
sorting(array);
return 0;
}
Kết quả
sorted order of zeroes count is: 1 3 2