构造一个数组,其从X开始的Prefix XOR数组是一个长度为N的递增序列
给定两个整数N和X ,任务是生成一个大小为 N的数组,使得 X 的前缀xor 数组与生成的数组将是 第一个 N 个自然数的排列。
例子:
Input: N = 4, X = 3
Output: [2, 3, 1, 7]
Explanation: Prefix XOR array for the array {2, 3, 1, 7} is as follows:
- X ⊕ 2 = 1. Now, X = 1
- X ⊕ 3 = 2. Now, X = 2
- X ⊕ 1 = 3. Now, X = 3
- X ⊕ 7 = 4. Now, X = 4
The array [1, 2, 3, 4] is a permutation of first 4 natural numbers.
Input: N = 7, X = 52
Output: [53, 3, 1, 7, 1, 3, 1]
方法:这个问题可以使用XOR 的性质来解决(如果x ⊕ a = b ,则x ⊕ b = a )。假设生成的数组中的元素与X直到第 i个索引为X进行异或,并且生成的数组的第(i + 1)个元素为B ,则可以使用以下步骤计算B :
X ⊕ B = i + 1
According to problem statement, using the property of XOR (if x⊕ a = b then, x⊕ b = a)…
X ⊕ i + 1 = B
Or
B = X ⊕ i + 1, which is the required value of B.
请按照以下步骤解决问题:
- 初始化一个变量,比如prev_xor为X 。
- 使用变量i迭代一个循环,从1到N并打印prev_xor ⊕ i 。
- 将 prev_xor 更新为 i 。
下面是上述方法的实现。
C++
// C++ program for the above approach
#include
using namespace std;
// Function to print the required array
void GenerateArray(int N, int X)
{
int prev_xor = X;
// Iterative from 1 to N
for (int i = 1; i <= N; i++) {
// Print the i-th element
cout << (i ^ prev_xor);
if (i != N) {
cout << " ";
}
// Update prev_xor to i
prev_xor = i;
}
}
// Driver Code
int main()
{
// Given Input
int N = 4, X = 3;
// Function Call
cout << "The generated array is ";
GenerateArray(N, X);
return 0;
}
Java
// Java program for the above approach
class GFG {
// Function to print the required array
static void GenerateArray(int N, int X)
{
int prev_xor = X;
// Iterative from 1 to N
for (int i = 1; i <= N; i++) {
// Print the i-th element
System.out.print(i ^ prev_xor);
if (i != N) {
System.out.print(" ");
}
// Update prev_xor to i
prev_xor = i;
}
}
// Driver Code
public static void main(String args[]) {
// Given Input
int N = 4, X = 3;
// Function Call
System.out.print("The generated array is ");
GenerateArray(N, X);
}
}
// This code is contributed by splevel62.
Python3
# Python 3 program for the above approach
# Function to print the required array
def GenerateArray(N, X):
prev_xor = X
# Iterative from 1 to N
for i in range(1,N+1,1):
# Print the i-th element
print(i ^ prev_xor,end="")
if (i != N):
print(" ",end="")
# Update prev_xor to i
prev_xor = i
# Driver Code
if __name__ == '__main__':
# Given Input
N = 4
X = 3
# Function Call
print("The generated array is ",end="")
GenerateArray(N, X)
# This code is contributed by ipg2016107
C#
// C# program for above approach
using System;
class GFG
{
// Function to print the required array
static void GenerateArray(int N, int X)
{
int prev_xor = X;
// Iterative from 1 to N
for (int i = 1; i <= N; i++) {
// Print the i-th element
Console.Write(i ^ prev_xor);
if (i != N) {
Console.Write(" ");
}
// Update prev_xor to i
prev_xor = i;
}
}
// Driver Code
static void Main()
{
// Given Input
int N = 4, X = 3;
// Function Call
Console.Write("The generated array is ");
GenerateArray(N, X);
}
}
// This code is contributed by sanjoy_62.
Javascript
输出:
The generated array is 2 3 1 7
时间复杂度: O(N)
辅助空间:O(1)