B. Roof Construction

Правка en1, от witty-v, 2022-03-27 15:06:54

For this probelm. needed to smallest XOR of sum of sequence from 0 to n (excluded) that has been permutated.

Intuition

The feature of XOR bitwise is the same is 0,otherwise 1. How we make the sum of sequence smallest? for 0 to n — 1 the n numbers. We should make pair that same length of binary bit go XOR operation. Such as 111(7) ^ 110(6) = 1 you will find their height bit turn into 0. So the solution is that make same length of binary bit go XOR operation.Base on this opeartion, we can obtain the answer.

Java

public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        int t = sc.nextInt();
        while (t-- > 0) {
            int n = sc.nextInt();
            int k = 0;
            while ((1 << k) < n ) { // k is closest but less than n 
                k++;
            }
            k--; 
            for (int i = (1 << k) - 1;i >= 0;i--) { // print same length of binary bit 
                System.out.print(i + " ");
            }
            for (int i = (1 << k);i < n;i++) {  // print same length of binary bit
                System.out.print(i + " ");
            }
            System.out.println();
        }
    }

CPP

int main() {
    ios::sync_with_stdio(false);
    cin.tie(0);
    int t;
    scanf("%d", &t);
    while (t--) {
        int n;
        scanf("%d", &n);
        int k = 0;
        while ((1 << k) < n) { // k is closest but less than n 
            k++;
        }
        k--;
        for (int i = (1 << k) - 1; i >= 0 ; --i) {  // print same length of binary bit
            printf("%d ",i);
        }
        for(int i = (1 << k);i < n;i++) {  // print same length of binary bit
            printf("%d ", i);
        }
        printf("\n");
    }
}
Теги bitwise, array

История

 
 
 
 
Правки
 
 
  Rev. Язык Кто Когда Δ Комментарий
en1 Английский witty-v 2022-03-27 15:06:54 1871 Initial revision (published)