Problem Statement and Algorithm Description

3: In-Depth Guide to Bitwise Operations and Greedy Algorithms

CSP-J2026 Official Solutions5.1 KBUploaded on2026/11/07 11:09

[CSP-J Algorithm Deep Dive.2026 Problem 3] Bitwise Operations & Greedy: How to Select m Numbers to Maximize the Bitwise AND Result?

In algorithm competitions, bitwise operations often embody a unique "brute-force aesthetics." Today, we'll dissect a classic greedy problem involving bitwise operations to see how binary properties can solve seemingly complex combinatorial problems in O(30n) time.

1. Question Content

Problem Description:Given n non-negative integers a₁, a₂, ..., aₙ, select exactly m numbers such that the **bitwise AND** of these m numbers is maximized. Output this maximum result.

Input format:The first line contains two integers n and m. The second line contains n integers aᵢ.

Data Range:1 ≤ m ≤ n ≤ 2 × 10⁵ 0 ≤ aᵢ < 2³⁰


2. Analysis of Approach

Core idea: Greedy by bit

We want to maximize the final bitwise AND result based on binary properties.One high-level 1 is worth more than all low-level 1 combined.(for example, 1000₂ > 0111₂). Therefore, our strategy is:Fill 1 whenever possible, starting from the most significant digit.。

Specific steps:

  1. Initialize: Set the final answer toans = 0。
  2. Enumerate from high-order to low-order bits: Enumerate from position 29 through position 0.
  3. Target:
    • If we want the j-th digit to be 1, we construct an "ideal target".target。
    • target = 已经确定的高位(ans) | 当前试探位(1 << j)。
  4. Verify feasibility:
    • Iterate through all numbers and count how many satisfy this.target。
    • Condition:(a[i] & target) == target。
    • This meanstargetThe bit at 1 isa[i]It must also be entirely 1.
  5. Decision:
    • If the count of numbers satisfying the condition is ≥ m, it means we can select m numbers such that their bitwise AND includes 1. Therefore, we proceed toansUpdate totarget。
    • Otherwise, it means 1 cannot be taken at the current position; skip and retain.ansUnchanged (i.e., the bit is 0).

3. Reference Code (C++)

This code adoptsSplit variableseparates the "current position" from the "target value," making it ideal for teaching and understanding.

C++Copy
#include<import>
using namespace std;

int n, m;
long long arr[200005]; // Array to store all numbers; use long long to prevent overflow

int main(){
    // 1. Enable fast I/O (essential for competitive programming)
    // Disable synchronization between C++ and C streams, and unbind cin from cout to significantly improve I/O performance
    ios::sync_with_stdio(false);
    cin.tie(0);
    
    // 2. Read data
    cin >> n >> m;
    for(int i = 0; i < n; i++){
        cin >> arr[i];
    }

    // ans stores the final answer, initialized to 0 (all bits set to 0)
    long long ans = 0;

    // 3. Core logic: Greedy enumeration from most significant to least significant digit (positions 29 to 0)
    // Why start from the high bit? Because one 1 at the high bit is greater than all 1s at lower bits combined.
    for(int j = 29; j >= 0; j--){
        
        // 4. Set bit 1
        // Example: j=4, so target_bit=16, binary representation is 10000
        long long target_bit = 1LL << j;
        
        Merge the determined high bits (>j) with the current bit 1 to form a trial target.
        long long target = ans | target_bit;
        
        int cnt = 0; // Counts how many numbers meet the current target

        // 5. Iterate through the array and check each number
        for(int i = 0; i < n; i++){
            // Critical check: (arr[i] & target) == target
            // Meaning: For all bit positions where arr[i] matches target 1, the corresponding bits in arr[i] must also be 1.
            // If true, the number can withstand this demanding target state
            if((arr[i] & target) == target){
                cnt++;
            }
        }

        // 6. Greedy decision
        // If the count of numbers meeting the condition is >= m, we can form at least m numbers.
        // ensure their bitwise AND includes the current 1, then update the answer accordingly
        if(cnt >= m){
            ans = target;
        }
        // If cnt < m, the current position cannot be set to 1; skip it and keep it as 0.
    }

    // 7. Output the final maximum bitwise AND result
    cout << ans << endl;
    return 0;
}

4. Complexity Analysis and Comparison

Time Complexity Analysis

What is the time complexity of this code?O(30 × n)。

  • The outer loop runs 30 times, from index 29 to index 0.
  • The inner loop iterates over n numbers.
  • Total operations: approximately 30 × 2 × 10⁵ = 6 × 10⁶.

This is highly secure under the standard of 1 computers performing approximately 10⁸ operations per second, with typical runtimes around 0.1 seconds.

Why does the "Basic Approach" time out?

If we don't use a greedy approach, but instead adopt the most basic oneBrute ForceApproach:

  • ApproachSelect m numbers from n numbers, compute their bitwise AND, and find the maximum value.
  • Complexity: Binomial coefficient Cₙᵐ.

When n=200,000 and m=100,000, this combination count is astronomical, far exceeding the total number of atoms in the universe. Even if m is small (e.g., m=3), the complexity remains O(n³), or (2 × 10⁵)³ = 8 × 10¹⁵, which will absolutely lead toTime Limit Exceeded。

Summary

The essence of this problem lies inLeverage the independence of bitwise operationsIt breaks down a complex combinatorial problem into 30 simple linear scan problems. That's the beauty of algorithms!

豫ICP备2026040576号-1