컨셉
주어진 두 정수 N과 K와 관련하여 우리의 임무는 비트 OR이 K와 같은 N개의 고유한 정수를 결정하는 것입니다. 가능한 답이 없으면 -1을 인쇄하는 것으로 나타났습니다.
입력
N = 4, K = 6
출력
6 0 1 2
입력
N = 11, K = 6
출력
-1
해결책을 찾을 수 없습니다.
방법
-
숫자 시퀀스의 비트별 OR이 K이면 K에서 0인 모든 비트 인덱스도 모든 숫자에서 0이어야 한다는 것을 알고 있습니다.
-
그 결과 K에서 비트가 1인 위치만 변경할 수 있습니다. 그 카운트를 Bit_K라고 합시다.
-
현재 Bit_K 비트를 사용하여 pow(2, Bit_K) 고유한 숫자를 만들 수 있습니다. 결과적으로 하나의 숫자를 K 자체로 취급하면 나머지 N – 1개의 숫자는 K에서 0인 각 숫자의 모든 비트를 0으로 설정하고 다른 비트 위치에 대해 번호 K.
-
pow(2, Bit_K)
예시
// C++ implementation of the approach
#include <bits/stdc++.h>
using namespace std;
#define ll long long int
#define MAX1 32
ll pow2[MAX1];
bool visited1[MAX1];
vector<int> ans1;
// Shows function to pre-calculate
// all the powers of 2 upto MAX
void power_2(){
ll ans1 = 1;
for (int i = 0; i < MAX1; i++) {
pow2[i] = ans1;
ans1 *= 2;
}
}
// Shows function to return the
// count of set bits in x
int countSetBits(ll x1){
// Used to store the count
// of set bits
int setBits1 = 0;
while (x1 != 0) {
x1 = x1 & (x1 - 1);
setBits1++;
}
return setBits1;
}
// Shows function to add num to the answer
// by placing all bit positions as 0
// which are also 0 in K
void add(ll num1){
int point1 = 0;
ll value1 = 0;
for (ll i = 0; i < MAX1; i++) {
// Bit i is 0 in K
if (visited1[i])
continue;
else {
if (num1 & 1) {
value1 += (1 << i);
}
num1 /= 2;
}
}
ans1.push_back(value1);
}
// Shows function to find and print N distinct
// numbers whose bitwise OR is K
void solve(ll n1, ll k1){
// Choosing K itself as one number
ans1.push_back(k1);
// Find the count of set bits in K
int countk1 = countSetBits(k1);
// It is not possible to get N
// distinct integers
if (pow2[countk1] < n1) {
cout << -1;
return;
}
int count1 = 0;
for (ll i = 0; i < pow2[countk1] - 1; i++) {
// Add i to the answer after
// placing all the bits as 0
// which are 0 in K
add(i);
count1++;
// Now if N distinct numbers are generated
if (count1 == n1)
break;
}
// Now print the generated numbers
for (int i = 0; i < n1; i++) {
cout << ans1[i] << " ";
}
}
// Driver code
int main(){
ll n1 = 4, k1 = 6;
// Pre-calculate all
// the powers of 2
power_2();
solve(n1, k1);
return 0;
} 출력
6 0 1 2