给定三个整数N , K和X ,任务是构造一个长度为N的数组,其中每个长度为K的连续子数组的所有元素的XOR为X。
例子:
Input: N = 5, K = 1, X = 4
Output: 4 4 4 4 4
Explanation:
Each subarray of length 1 has Xor value equal to 4.
Input: N = 5, K = 2, X = 4
Output: 4 0 4 0 4
Explanation:
Each subarray of length 2 has Xor value equal to 4.
方法:
要解决上述问题,我们需要执行以下步骤:
- 任意数字的按位XOR, X与0等于数字本身。因此,如果将数组A的第一个元素设置为X,并将接下来的K – 1个元素设置为0 ,则将使长度为K的第一个子数组的元素的XOR等于X。
- 如果将A [K]设置为A [0] ,则将具有XOR(A [1],…,A [K])=X。类似地,如果将A [K + 1]设置为A [1] ,那么我们将得到XOR(A [2],…,A [K + 1])= X
- 以这种方式继续,我们可以观察到通式可以描述如下:
下面是上述方法的实现:
C++
// C++ implementation to Create an array
// in which the XOR of all elements of
// each contiguous sub-array of
// length K is X
#include
using namespace std;
// Function to construct the array
void constructArray(int N, int K, int X)
{
// Creating a vector of size K,
// initialised with 0
vector ans(K, 0);
// Initialising the first element
// with the given XOR
ans[0] = X;
for (int i = 0; i < N; ++i) {
cout << ans[i % K] << " ";
}
cout << endl;
}
// Driver code
int main()
{
int N = 5, K = 2, X = 4;
constructArray(N, K, X);
return 0;
}
Java
// Java implementation to create an array
// in which the XOR of all elements of
// each contiguous sub-array of
// length K is X
class GFG{
// Function to construct the array
public static void constructArray(int N, int K,
int X)
{
// Creating an array of size K,
// initialised with 0
int[] ans = new int[K];
// Initialising the first element
// with the given XOR
ans[0] = X;
for(int i = 0; i < N; ++i)
{
System.out.print(ans[i % K] + " ");
}
}
// Driver code
public static void main(String[] args)
{
int N = 5, K = 2, X = 4;
constructArray(N, K, X);
}
}
// This code is contributed by divyeshrabadiya07
Python3
# Python3 implementation to create an array
# in which the XOR of all elements of
# each contiguous sub-array of
# length K is X
# Function to construct the array
def constructArray(N, K, X):
# Creating a list of size K,
# initialised with 0
ans = []
for i in range(0, K):
ans.append(0)
# Initialising the first element
# with the given XOR
ans[0] = X
for i in range(0, N):
print(ans[i % K], end = " ")
# Driver code
N = 5
K = 2
X = 4
# Function call
constructArray(N, K, X)
# This code is contributed by ishayadav181
C#
// C# implementation to create an array
// in which the XOR of all elements of
// each contiguous sub-array of
// length K is X
using System;
class GFG{
// Function to construct the array
public static void constructArray(int N, int K,
int X)
{
// Creating an array of size K,
// initialised with 0
int[] ans = new int[K];
// Initialising the first element
// with the given XOR
ans[0] = X;
for(int i = 0; i < N; ++i)
{
Console.Write(ans[i % K] + " ");
}
}
// Driver code
public static void Main(string[] args)
{
int N = 5, K = 2, X = 4;
constructArray(N, K, X);
}
}
// This code is contributed by rutvik_56
Javascript
输出:
4 0 4 0 4
时间复杂度: O(N)
如果您希望与行业专家一起参加现场课程,请参阅《 Geeks现场课程》和《 Geeks现场课程美国》。