using LL = longlong; constint N = 1e5 + 5; classSolution { public: vector<int> g[N]; int f[N], sz[N]; intfind(int x){ return x == f[x] ? x : f[x] = find(f[x]); } voidmerge(int x, int y){ x = find(x), y = find(y); if (x != y) { sz[x] += sz[y]; f[y] = x; } } longlongcountPairs(int n, vector<vector<int>>& edges){ for (int i = 0; i < n; i ++ ) f[i] = i, sz[i] = 1; for (auto& e : edges) { int a = e[0], b = e[1]; merge(a, b); } vector<int> cnt; for (int i = 0; i < n; i ++ ) { if (f[i] == i) cnt.push_back(sz[i]); } LL ans = 0LL; for (int i = 0; i < cnt.size(); i ++ ) ans += 1ll * cnt[i] * (n - cnt[i]); return ans >> 1; } };
nums[i] AND (nums[i] XOR x)的唯一作用是”选择屏蔽”nums[i]中的某些1(二进制表示下). 因此nums所有元素最大逐位异或和即为所有出现过的1的二进制表示之和, 因为我们无法在某一位不存在的1的情况下让他变成1, 因此出现过1的位置选1就是最大最优解.
Code
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
classSolution { public: intmaximumXOR(vector<int>& nums){ vector<int> cnt(32); for (auto& num : nums) { for (int i = 0; i < 32; i ++ ) if (num >> i & 1) cnt[i] = 1; } int ans = 0; for (int i = 0; i < 32; i ++ ) if (cnt[i]) ans += 1 << i; return ans; } };
using LL = longlong; constint N = 1e4 + 5, M = 7, MOD = 1e9 + 7; classSolution { public: LL f[N][M][M]; intdistinctSequences(int n){ if (n == 1) return6; vector<int> ok[M]; for (int i = 1; i < M; i ++ ) for (int j = 1; j < M; j ++ ) if (gcd(i, j) == 1 && i != j) ok[i].push_back(j), f[2][i][j] = 1; for (int i = 3; i <= n; i ++ ) for (int j = 1; j < M; j ++ ) for (auto& k : ok[j]) { for (auto& l : ok[k]) { if (j == k or j == l or k == l) continue; f[i][j][k] = (f[i][j][k] + f[i - 1][k][l]) % MOD; } } LL ans = 0LL; for (int i = 1; i < M; i ++ ) for (auto& j : ok[i]) ans = (ans + f[n][i][j]) % MOD; return ans; } };