Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- using ll = long long;
- class Solution {
- public:
- int minOrAfterOperations(vector<int>& nums, int k) {
- int n = nums.size();
- vector<int> bc(32);
- for (auto x: nums) {
- for (int i = 0; i < 30; ++i)
- if ((1 << i) & x) bc[i]++;
- }
- int ans = 0;
- for (int i = 29; i >= 0 && k > 0; --i) {
- if (nums.size() - bc[i] >= k) {
- vector<int> ns;
- for (int i = 0; i < nums.size();) {
- if (nums[i] & (1 << i)) {
- int j = i;
- int tmp = nums[i];
- while(j < nums.size() && (nums[j] & (1 << i) != 0)) ++j, tmp = tmp & nums[j];
- ns.push_back(tmp);
- i = j;
- } else {
- ns.push_back(nums[i]);
- ++i;
- }
- }
- vector<int> ns2;
- for (int i = 0; i < ns.size(); ++i) {
- if (ns[i] & (1 << i)) {
- if (i == 0) {
- ns[i+1] &= ns[i];
- } else if (i == ns.size() - 1) {
- ns2.back() &= ns[i];
- } else {
- int ov = ns2.back() & ns[i];
- int nv = ns[i] & ns[i + 1];
- if (ov < nv) {
- ns2.back() &= ns[i];
- } else {
- ns[i + 1] &= ns[i];
- }
- }
- } else {
- ns2.push_back(ns[i]);
- }
- }
- k -= nums.size() - bc[i];
- nums = ns2;
- bc = vector<int>(32);
- for (auto x: nums) {
- for (int i = 0; i < 30; ++i)
- if ((1 << i) & x) bc[i]++;
- }
- } else {
- break;
- }
- }
- for (auto x: nums) ans |= x;
- return ans;
- }
- };
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement