แนวคิด
สำหรับจำนวนเต็มสองจำนวนที่กำหนด N และ K หน้าที่ของเราคือกำหนดจำนวนเต็มเฉพาะ N ที่มีค่าระดับบิต OR เท่ากับ K จะเห็นได้ว่าหากไม่มีคำตอบที่เป็นไปได้ ให้พิมพ์ -1
อินพุต
N = 4, K = 6
ผลลัพธ์
6 0 1 2
อินพุต
N = 11, K = 6
ผลลัพธ์
-1
ไม่สามารถหาทางแก้ไขได้
วิธีการ
-
เรามีความรู้ว่าหาก OR ที่ฉลาดระดับบิตของลำดับตัวเลขเป็น K ดังนั้นดัชนีบิตทั้งหมดที่เป็น 0 ใน K จะต้องเป็นศูนย์ในตัวเลขทั้งหมดด้วย
-
ด้วยเหตุนี้ เราจึงมีเพียงตำแหน่งเหล่านั้นที่จะเปลี่ยนโดยที่บิตเป็น 1 ใน K ให้นับเป็น Bit_K
-
ปัจจุบัน เราสามารถสร้าง pow(2, Bit_K) ตัวเลขเฉพาะด้วย Bit_K bits ด้วยเหตุนี้ หากเราถือว่าตัวเลขหนึ่งตัวเป็น K เอง จากนั้นตัวเลข N-1 ที่เหลือก็สามารถสร้างได้โดยการตั้งค่า 0 บิตทั้งหมดในแต่ละตัวเลขซึ่งมีค่า 0 ใน K และสำหรับตำแหน่งบิตอื่นๆ การเปลี่ยนแปลงใดๆ ของบิต Bit_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