classSolution { public: boolcheckOnesSegment(string s){ int state = 0; // 0: not see 1 // 1: see 1 and now 1 // 2: see 1 but now 0 for (char c : s) { if (c == '0') { if (state == 0) { state = 0; } elseif (state == 1) { state = 2; } else { state = 2; } } else { // c == '1' if (state == 0) { state = 1; } elseif (state == 1) { state = 1; } else { returnfalse; } } } returntrue; } };
classSolution { constint MAX_NUMS = 1 << 10; public: intminChanges(vector<int>& nums, int k){ constint n = nums.size(); // the total size of Set[i] vector<int> totalCost(k); // cnt[i][j]: the count of j in Set[i] vector<unordered_map<int, int>> cnt(k); for (int i = 0; i < n; ++i) { ++totalCost[i % k]; ++cnt[i%k][nums[i]]; } // the cost to set Set[i] to v auto cost = [&](constint i, constint v) -> int { return totalCost[i] - cnt[i][v]; }; // dp[i][d]: the minimum cost to make first i XOR equal to d vector<vector<int>> dp(k, vector<int> (MAX_NUMS, numeric_limits<int>::max())); int minLastDp = numeric_limits<int>::max(); for (int d = 0; d < MAX_NUMS; ++d) { dp[0][d] = totalCost[0] - cnt[0][d]; minLastDp = min(minLastDp, dp[0][d]); } for (int i = 1; i < k; ++i) { int minDp = numeric_limits<int>::max(); for (int d = 0; d < MAX_NUMS; ++d) { dp[i][d] = minLastDp + totalCost[i]; for (int j = i; j < n; j += k) { dp[i][d] = min(dp[i][d], dp[i-1][d^nums[j]] + cost(i, nums[j])); } minDp = min(minDp, dp[i][d]); } minLastDp = minDp; } return dp[k-1][0]; } };