給定一組整數 colors,每個整數可視為二進制向量。求這些向量張成的線性空間的基的大小,即矩陣的秩。等價於求最大線性無關子集的大小。
從最高位(第 31 位)向最低位掃描,維護一組基向量。對於每一位:
最終基的個數即為答案。
#include <vector>
#include <cstring>
using namespace std;
class MixingColors {
public:
int minColors(vector<int> colors) {
int res = 0;
int n = colors.size();
bool used[55] = {false};
for (int i = 31; i >= 0; i--) {
int pivot = 0;
for (int j = 0; j < n; j++) {
if (used[j]) continue;
if ((colors[j] >> i) & 1) {
if (!pivot) {
pivot = colors[j];
used[j] = true;
++res;
} else {
colors[j] ^= pivot; // 消去第 i 位
}
}
}
}
return res;
}
};
basis[32] 陣列,insert(x) 從高位到低位嘗試插入,若 basis[i] 為空則佔位,否則 x ^= basis[i]。本題是線性基/高斯消元在 GF(2) 域上應用的經典入門題。掌握「從高位到低位貪心構建基」的模板,可解決大多數異或相關的線性代數問題。代碼簡潔、無浮點誤差、複雜度低,是競賽編程中的必備技能。