给定一个由N 个正整数组成的序列 arr ,任务是找到最长子序列的长度,使得子序列中相邻整数的 xor 必须是非递减的。
例子:
Input: N = 8, arr = {1, 100, 3, 64, 0, 5, 2, 15}
Output: 6
The subsequence of maximum length is {1, 3, 0, 5, 2, 15}
with XOR of adjacent elements as {2, 3, 5, 7, 13}
Input: N = 3, arr = {1, 7, 10}
Output: 3
The subsequence of maximum length is {1, 3, 7}
with XOR of adjacent elements as {2, 4}.
方法:
- 这个问题可以使用动态规划解决,其中dp[i]将存储在索引 i处结束的最长有效子序列的长度。
- 首先,存储所有元素对的异或,即arr[i] ^ arr[j]和(i, j)对,然后根据 xor 的值对它们进行排序,因为它们需要是非递减的。
- 现在,如果考虑 (i, j)对,那么以 j结尾的最长子序列的长度将是max(dp[j], 1 + dp[i]) 。这样,计算每个位置的 dp[]数组的最大可能值,然后取它们中的最大值。
下面是上述方法的实现:
C++
// C++ implementation of the approach
#include
using namespace std;
// Function to find the length of the longest
// subsequence such that the XOR of adjacent
// elements in the subsequence must
// be non-decreasing
int LongestXorSubsequence(int arr[], int n)
{
vector > > v;
for (int i = 0; i < n; i++) {
for (int j = i + 1; j < n; j++) {
// Computing xor of all the pairs
// of elements and store them
// along with the pair (i, j)
v.push_back(make_pair(arr[i] ^ arr[j],
make_pair(i, j)));
}
}
// Sort all possible xor values
sort(v.begin(), v.end());
int dp[n];
// Initialize the dp array
for (int i = 0; i < n; i++) {
dp[i] = 1;
}
// Calculating the dp array
// for each possible position
// and calculating the max length
// that ends at a particular index
for (auto i : v) {
dp[i.second.second]
= max(dp[i.second.second],
1 + dp[i.second.first]);
}
int ans = 1;
// Taking maximum of all position
for (int i = 0; i < n; i++)
ans = max(ans, dp[i]);
return ans;
}
// Driver code
int main()
{
int arr[] = { 2, 12, 6, 7, 13, 14, 8, 6 };
int n = sizeof(arr) / sizeof(arr[0]);
cout << LongestXorSubsequence(arr, n);
return 0;
}
Python3
# Python3 implementation of the approach
# Function to find the length of the longest
# subsequence such that the XOR of adjacent
# elements in the subsequence must
# be non-decreasing
def LongestXorSubsequence(arr, n):
v = []
for i in range(0, n):
for j in range(i + 1, n):
# Computing xor of all the pairs
# of elements and store them
# along with the pair (i, j)
v.append([(arr[i] ^ arr[j]), (i, j)])
# v.push_back(make_pair(arr[i] ^ arr[j], make_pair(i, j)))
# Sort all possible xor values
v.sort()
# Initialize the dp array
dp = [1 for x in range(88)]
# Calculating the dp array
# for each possible position
# and calculating the max length
# that ends at a particular index
for a, b in v:
dp[b[1]] = max(dp[b[1]], 1 + dp[b[0]])
ans = 1
# Taking maximum of all position
for i in range(0, n):
ans = max(ans, dp[i])
return ans
# Driver code
arr = [ 2, 12, 6, 7, 13, 14, 8, 6 ]
n = len(arr)
print(LongestXorSubsequence(arr, n))
# This code is contributed by Sanjit Prasad
Javascript
输出
5
时间复杂度: O(N* N)
辅助空间: O(N)
如果您希望与专家一起参加现场课程,请参阅DSA 现场工作专业课程和学生竞争性编程现场课程。